Interview Question
Country: United States
#include<stdio.h>
#include<conio.h>
#include<iostream>
using namespace std;
int main()
{
int n=5;
int i,j;
int q[20];
cout<<"\n enter the data";
for(i=0;i<10;i++)
{
cin>>q[i];
}
int a,b,c[10],d;
for(i=0;i<n;i++)
{
for(j=0;j<10;j++)
{
a=i;
b=i+n;
c[j]=q[i];
c[j+1]=q[b];
i=i+1;
j=j+1;
}
}
for(i=0;i<10;i++)
cout<<"\n"<<c[i];
getch();
}
#include<iostream>
using namespace std;
//s=12345678
//s[3],s[4]
//s[2],s[3] s[4],s[5]
//s[1],s[2] s[3],s[4] s[5],s[6]
void rearrange(string &str)
{
int l = str.length();
int center = (l/2)-1;
int j, m, n;
m = center;
n = 0;
for(int i = 1; i<=center; i++)
{
j = 0;
while(j<i)
{
char t = str[m];
str[m] = str[m+1];
str[m+1] = t;
j++;
m = m+2;
}
m = center - i;
}
}
int main()
{
string str = "abcdefghijklmn";
cout<<str<<endl;
rearrange(str);
cout<<str<<endl;
return 0;
}
Complexity : O(n)
public class TestOnly{
public static void main(String args[]){
int a[] = {1,2,3,4,5,6,7,8};
merge(a,1,4);
System.out.println(Arrays.toString(a));
}
public static void merge(int a[], int first, int second) {
while(first<second){
int tmp = a[second];
shiftArray(a,first,second);
a[first] = tmp;
first = first + 2;
second++;
}
}
public static void shiftArray(int[] a,int first,int second){
while(second>first){
a[second] = a[second-1];
second--;
}
}
}
public class SwapInPlace {
public static void main(String[] args){
int N = 5;
int[] a = new int[]{11, 12, 13, 14, 15, 21, 22, 23, 24, 25};
for(int i = 0; i < N-1; i++){
int tmp = a[N + i];
for(int j = N+i; j >= 2*i+2; j--){
a[j] = a[j-1];
}
a[2*i+1] = tmp;
}
for(int i = 0; i < 2*N; i++){
System.out.println(a[i]);
}
}
}
- Nitin Gupta January 17, 2014