Interview Questions

144. If [a1,a2,a3...,an,b1,b2...bn] is given input change......

Microsoft Interview Questions and Answers


(Continued from previous question...)

144. If [a1,a2,a3...,an,b1,b2...bn] is given input change......

Question:
If [a1,a2,a3...,an,b1,b2...bn] is given input change this to [a1,b1,a2,b2.....an,bn] , solution should be in-place


maybe an answer:


package arrays;

public class Exchange {
public static void exchange(int[] a){
exchange(a, (a.length/2) - 1, a.length/2);
}

private static void exchange(int[] a,int x,int y){
if(x==0 || y==a.length-1){
return;
}

for(int i=x;i<=y;i=i+2){
int temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
exchange(a, x-1, y+1);
}

public static void main(String[] args){
int[] a = {1,2,3,4,5,6,7,8,9,10};
exchange(a);
for(int i : a){
System.out.print(i + " ");
}
}
}

Output: 1 6 2 7 3 8 4 9 5 10

(Continued on next question...)

Other Interview Questions