forked from aswinkumarrk/data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWaveArray.java
More file actions
47 lines (40 loc) · 1.14 KB
/
WaveArray.java
File metadata and controls
47 lines (40 loc) · 1.14 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.interviewbit.array;
import com.geeksforgeeks.array.QuickSort;
import com.util.LogUtil;
import java.util.Arrays;
/**
* https://www.interviewbit.com/problems/wave-array/
*
* @author neeraj on 2019-07-25
* Copyright (c) 2019, data-structures.
* All rights reserved.
*/
public class WaveArray {
public static void main(String[] args) {
LogUtil.printArray(waveArray(new int[]{1, 2, 3, 4}));
LogUtil.printArray(waveArray(new int[]{5, 1, 3, 2, 4}));
}
private static int[] waveArray(int[] arr) {
Arrays.sort(arr);
Boolean uptrend = false;
for (int i = 0; i < arr.length - 1; i++) {
if (uptrend) {
if (arr[i] > arr[i + 1]) {
swap(arr, i, i + 1);
}
uptrend = false;
} else {
if (arr[i] < arr[i + 1]) {
QuickSort.swap(arr, i, i + 1);
}
uptrend = true;
}
}
return arr;
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}