Rearrange Array in Wave Form
C++
Hard
10 views
Problem Description
Arrange elements such that arr[0] >= arr[1] = arr[3]... This teaches pattern-based sorting and swapping logic.
Logic: Swap adjacent elements at odd positions if needed
Official Solution
void question15_wave_array() {
int arr[] = {10, 5, 6, 3, 2, 20, 100, 80};
int size = 8;
for(int i = 0; i < size - 1; i += 2) {
if(i > 0 && arr[i] < arr[i - 1]) {
int temp = arr[i];
arr[i] = arr[i - 1];
arr[i - 1] = temp;
}
if(i < size - 1 && arr[i] < arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
cout << "Wave array: ";
for(int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!