[Geeks for Geeks] Convert array into Zig-Zag fashion

Convert array into Zig-Zag fashion

Given an array Arr (distinct elements) of size N. Rearrange the elements of array in zig-zag fashion. The converted array should be in form a < b > c < d > e < f. The relative order of elements is same in the output i.e you have to iterate on the original array only.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
class Solution{
public:
// Program for zig-zag conversion of array
void zigZag(int arr[], int n) {
for(int i = 0, j = 1; i < n - 1; i++,j++) {
if(arr[i] > arr[j] and !(i & 1)) swap(arr[i], arr[j]);
else if(arr[i] < arr[j] and (i & 1)) swap(arr[i], arr[j]);
}
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/21/PS/GeeksforGeeks/convert-array-into-zig-zag-fashion/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.