Two solutions:
1. Swap middle pair, and keep swapping increasing number of pairs from the middle:
C++ implementation:
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