Skip to content

Commit a9faf5e

Browse files
author
Tushar Roy
committed
zig zag arrangement of array
1 parent 97405ec commit a9faf5e

2 files changed

Lines changed: 69 additions & 0 deletions

File tree

python/array/zigzagarrangement.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# http://www.geeksforgeeks.org/convert-array-into-zig-zag-fashion/
2+
3+
def rearrange(input):
4+
is_less = True
5+
for i in range(len(input)-1):
6+
if is_less:
7+
if input[i] > input[i+1]:
8+
swap(input, i, i+1)
9+
else:
10+
if input[i] < input[i+1]:
11+
swap(input, i, i+1)
12+
is_less = not is_less
13+
14+
def swap(input, i, j):
15+
t = input[i]
16+
input[i] = input[j]
17+
input[j] = t
18+
19+
if __name__ == '__main__':
20+
input = [4, 3, 2, 6, 7, 1, 9]
21+
rearrange(input)
22+
print(input)
23+
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.interview.array;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* Date 12/30/2015
7+
* @author Tushar Roy
8+
*
9+
* Given an array of unique elements rearrange the array to be a < b > c < d > e form
10+
*
11+
* Time complexity - O(n)
12+
* Space complexity - O(1)
13+
*
14+
* http://www.geeksforgeeks.org/convert-array-into-zig-zag-fashion/
15+
*/
16+
public class ZigZagArrangement {
17+
18+
public void rearrange(int input[]) {
19+
boolean isLess = true;
20+
for (int i = 0; i < input.length - 1; i++) {
21+
if(isLess) {
22+
if (input[i] > input[i+1]) {
23+
swap(input, i, i+1);
24+
}
25+
} else {
26+
if (input[i] < input[i+1]) {
27+
swap(input, i, i+1);
28+
}
29+
}
30+
isLess = !isLess;
31+
}
32+
}
33+
34+
private void swap(int input[], int i, int j) {
35+
int t = input[i];
36+
input[i] = input[j];
37+
input[j] = t;
38+
}
39+
40+
public static void main(String args[]) {
41+
int input[] = {4, 3, 2, 6, 7, 1, 9};
42+
ZigZagArrangement zza = new ZigZagArrangement();
43+
zza.rearrange(input);
44+
Arrays.stream(input).forEach(i -> System.out.print(i + " "));
45+
}
46+
}

0 commit comments

Comments
 (0)