Input: arr[] = {1, 2, 3, 4, 5, 6, 7}
Output: arr[] = {7, 1, 6, 2, 5, 3, 4}
Explanation: First 7 is the max value, then 1 is the min value, then 6 is the second max value, then 2 is the second min value, then 5 is the third max value, then 3 is the third min value and at last 4 is the fourth max value.
Input: arr[] = {1, 2, 3, 4, 5, 6}
Output: arr[] = {6, 1, 5, 2, 4, 3}
The idea is to use multiplication and modular arithmetic to store two elements at each index. Assume M = maximum element in the array + 1. Now, if we want to store two numbers say X and Y at any index, then we can store X + (Y * M) at that index. This will work because using X + (Y * M), we can get the first value by using modulo: (X + (Y * M)) mod M = X and the second value by using (X + (Y * M)) / M = Y.
To arrange the elements alternately, we can maintain two pointers min_idx = 0 to keep track of the next minimum element and max_idx = N - 1 to keep track of next maximum element. Now, iterate from i = 0 to N - 1,
- If i is even, then we need to place maximum remaining element, so update arr[i] = arr[i] + (arr[max_idx] % M) * M and decrement max_idx by 1. Now, arr[i] has arr[i] as well as arr[max_idx] as its value.
- If i is odd, then we need to place minimum remaining element, so update arr[i] = arr[i] + (arr[min_idx] % M) * M and increment min_idx by 1. Now, arr[i] has arr[i] as well as arr[min_idx] as its value.
Finally, again iterate from i = 0 to N - 1 and update arr[i] = arr[i] / M.