Loading Similar Posts
Given a sorted array of positive integers. Your task is to rearrange the array elements alternatively i.e first element should be max value, second should be min value, third should be second max, fourth should be second min and so on...
Note: O(1) extra space is allowed. Also, try to modify the input array as required.
Input: First line of input conatins number of test cases T. First line of test case contain an integer denoting the array size N and second line of test case contain N space separated integers denoting the array elements.
Output: Output the modified array with alternated elements.
Constraints:
Example:
Input:
2
6
1 2 3 4 5 6
11
10 20 30 40 50 60 70 80 90 100 110
Output:
6 1 5 2 4 3
110 10 100 20 90 30 80 40 70 50 60
Lets take an example sequence. 1 2 3 4 5 6 Let orig_pos be the extra O(1) space that we take. Step 1 swap(6,1), orig_pos of 1= 1 6 2 3 4 5 1 Step 2 final position of 1 should be position-2 swap(1,2), orig_pos of 2 = 4 6 1 3 4 5 2 Step 3 final position of 2 should be position-4 swap(2,4), orig_pos of 4 = 4 6 1 3 2 5 4 Step 4 final position of 4 should be position-5 swap(4,5), orig_pos of 5 = 5 6 1 3 2 4 5 Step 5 final position of 5 should be position-3 swap(5,3), orig_pos of 3 = 6 6 1 5 2 4 3 Now we terminate as final position of 3 = original position.
Time Complexity | O(N) |
Space Complexity | O(1) |