VOOZH about

URL: https://www.geeksforgeeks.org/dsa/convert-array-into-zig-zag-fashion/

⇱ Convert Array into Zig-Zag fashion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert Array into Zig-Zag fashion

Last Updated : 23 Jul, 2025

Given an array of distinct elements of size N, the task is to rearrange the elements of the array in a zig-zag fashion, i.e., the elements are arranged as smaller, then larger, then smaller, and so on. There can be more than one arrangement that follows the form:

arr[0] < arr[1]  > arr[2] < arr[3] > arr[4] < ...

Examples:

Input: N = 7, arr[] = [4, 3, 7, 8, 6, 2, 1]
Output: [3, 7, 4, 8, 2, 6, 1]
Explanation: The given array is in zig-zag pattern as we can see 3 < 7 > 4 < 8 > 2 < 6 >1

Input: N = 4, arr[] = [1, 4, 3, 2]
Output: [1, 4, 2, 3]

[Naive Approach] Using Sorting - O(N*log(N)) time and O(1) Space

The most basic approach is to solve this with the help of Sorting. The idea is to sort the array first and then swap adjacent elements (from 1st index) to make the array as zig-zag array.

Code Implementation:


Output
1 3 2 6 4 8 7 

Time complexity: O(N*log(N)), because sorting is used.
Auxiliary Space: O(1)

[Expected Approach] Rearranging Triplets using Flag - O(N) time and O(1) Space

The most efficient and expected approach is to use the triplet relation of zig-zag array, i.e. arr[i-1] < arr[i] > arr[i+1].

The idea is that for each triplet, the middle element should be greater than its adjacent neighbours. So, for each triplet:

  1. First check the left neighbour with the middle element. If middle is smaller, swap the elements.
  2. Then check the middle with right neighbour. If middle is smaller, swap the elements.
  3. Repeat the process till complete array is traversed.

Code Implementation:


Output
3 7 4 8 2 6 1 

Time complexity: O(N)
Auxiliary Space: O(1)

Illustration of the Expected Approach:


Comment
Article Tags: