-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWave Array
More file actions
25 lines (22 loc) · 803 Bytes
/
Copy pathWave Array
File metadata and controls
25 lines (22 loc) · 803 Bytes
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
//Given a sorted array arr[] of distinct integers. Sort the array into a wave-like array and return it.
//In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5..... (considering the increasing lexicographical order).
//Input: N = 5 arr[] = {1,2,3,4,5} Output: 2 1 4 3 5
public static void convertToWave(int arr[], int n){
// Your code here
//Method 1
int i=0;int j=i+1;
while(j<n){
if(arr[i]<arr[j]){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i=i+2;j=j+2;
}
}
//Method 2
for(int i=0;i<n-1;i=i+2){
int t=arr[i];
arr[i]=arr[i+1];
arr[i+1]=t;
}
}