-
Notifications
You must be signed in to change notification settings - Fork 22
/
ConvertArrayIntoZigZagFashion.java
52 lines (44 loc) · 1.3 KB
/
ConvertArrayIntoZigZagFashion.java
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
48
49
50
51
52
package com.company.amazon;
import static com.geeksforgeeks.array.ArrayRotation.printArray;
/**
* Example:
* Input: arr[] = {4, 3, 7, 8, 6, 2, 1}
* Output: arr[] = {3, 7, 4, 8, 2, 6, 1}
* <p>
* Input: arr[] = {1, 4, 3, 2}
* Output: arr[] = {1, 4, 2, 3}
*/
public class ConvertArrayIntoZigZagFashion {
public static void main(String[] args) {
int[] arr = {4, 3, 7, 8, 6, 2, 1};
printArray(arr);
convertIntoZigZagFashion(arr);
printArray(arr);
arr = new int[]{1, 4, 3, 2};
printArray(arr);
convertIntoZigZagFashion(arr);
printArray(arr);
arr = new int[]{3, 7, 4, 5, 2, 9, 12, 6};
printArray(arr);
convertIntoZigZagFashion(arr);
printArray(arr);
}
public static void swap(int i, int j, int[] arr) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void convertIntoZigZagFashion(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (i % 2 == 0) { // Even Numbers
if (arr[i] > arr[i + 1]) {
swap(i, i + 1, arr);
}
} else { // Odd Numbers
if (arr[i] < arr[i + 1]) {
swap(i, i + 1, arr);
}
}
}
}
}