Saturday, March 1, 2014

Interview 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

Two solutions:
1. Swap middle pair, and keep swapping increasing number of pairs from the middle:

C++ implementation:
void arrangeArray(int *a){
int num_swaps = 1; //number of swaps to be done
int i = 0;
int mid=0;
int swap_start_idx = 0;
int swap_end_idx = 0;
int temp=0;

//find lenght of array
while(a[i] != '\0'){
i++;
}
mid = i/2 -1;
cout << "mid: " << mid << endl;
i=0;
while(a[i] != '\0'){
cout << a[i] << endl;
i++;
}

while(mid -num_swaps +1 > 0){
swap_start_idx = mid-num_swaps+1;
swap_end_idx = mid+num_swaps;
//cout << "num_swaps: " << num_swaps << " swap_start_idx " << swap_start_idx << "  swap_end_idx "<< swap_end_idx << endl;
while(swap_end_idx > swap_start_idx){
temp=a[swap_start_idx];
a[swap_start_idx]=a[swap_start_idx+1];
a[swap_start_idx+1] = temp;
//cout << "a[swap_start_idx]: " <<  a[swap_start_idx] << "  a[swap_end_idx]: " << a[swap_end_idx] << endl; 
swap_start_idx += 2;
}
num_swaps++;
//cout << "num_swaps" << num_swaps << endl;
}
return;

}


int main () {
    int a[] = {1,3,5,7,2,4,6,8};
int i=0;
while(a[i] != '\0'){
cout << a[i] << endl;
i++;
}
arrangeArray(a);
i=0;
while(a[i] != '\0'){
cout << a[i] << endl;
i++;
}
 return 0;
}

No comments:

Post a Comment