PROBLEM DESCRIPTION
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: Modify the original array itself. Do it without using any extra space. You do not have to return anything.
SOLUTION
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution{
// temp: input array
// n: size of array
//Function to rearrange the array elements alternately.
public static void rearrange(long arr[], int n){
int minIndex = 0;
int maxIndex = n-1;
long M = arr[n-1] + 1;
for(int i=0; i<n; i++){
if(i%2 == 0){
arr[i] = (arr[maxIndex]%M)*M + arr[i];
maxIndex--;
}else{
arr[i] = (arr[minIndex]%M)*M + arr[i];
minIndex++;
}
}
for(int i=0; i<n; i++)
arr[i] = arr[i]/M;
}
}