Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZigZagArray.java
More file actions
Latest commit
52 lines (42 loc) · 1.57 KB
/
Copy pathZigZagArray.java
File metadata and controls
52 lines (42 loc) · 1.57 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
48
49
50
51
52
importjava.util.Scanner;
publicclassZigZagArray {
publicstaticvoidmain(String[] args) {
Scannerscanner = newScanner(System.in);
System.out.println("ZigZag Array Arrangement");
System.out.println("-----------------------");
System.out.print("Enter the size of the array: ");
intsize = scanner.nextInt();
int[] arr = newint[size];
System.out.println("Enter " + size + " integers:");
for (inti = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}
arrangeZigZag(arr);
System.out.println("ZigZag arranged array:");
for (intnum : arr) {
System.out.print(num + " ");
}
scanner.close();
}
privatestaticvoidarrangeZigZag(int[] arr) {
booleanflag = true; // true means '<' expected, false means '>' expected
for (inti = 0; i < arr.length - 1; i++) {
if (flag) { // '<' relation expected
if (arr[i] > arr[i + 1]) {
// Swap
inttemp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
} else { // '>' relation expected
if (arr[i] < arr[i + 1]) {
// Swap
inttemp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
flag = !flag; // Flip the flag for next comparison
}
}
}