Convert Array into Zig-Zag fashion

Last Updated : 1 Aug, 2026

Given an array arr of distinct elements, the task is to rearrange the elements of the array in a zig-zag fashion so that the converted array should be in the below form: 

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

Note: Modify the given arr[] only, If your transformation is correct, the output will be "true" else the output will be "false". 

Examples:

Input: arr[] = [4, 3, 7, 8, 6, 2, 1]
Output: true
Explanation: After modification the array will look like 3 < 7 > 4 < 8 > 2 < 6 > 1, the checker in the driver code will produce 1.

Input: arr[] = [4, 7, 3, 8, 2]
Output: true
Explanation: After modification the array will look like 4 < 7 > 3 < 8 > 2 hence output will be 1.

Try It Yourself
redirect icon

[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.

C++
#include <bits/stdc++.h>
using namespace std;

// Function to convert the given array into zig-zag fashion
// such that a < b > c < d > e ...
void zigZag(vector<int> &arr)
{
    // Flag indicates expected relation between elements
    // true  -> "<" relation expected
    // false -> ">" relation expected
    bool flag = true;

    int n = arr.size();

    // Traverse the array
    for (int i = 0; i <= n - 2; i++)
    {

        // If current relation expected is "<"
        if (flag)
        {
            // If relation is violated, swap elements
            if (arr[i] > arr[i + 1])
                swap(arr[i], arr[i + 1]);
        }
        // If current relation expected is ">"
        else
        {
            // If relation is violated, swap elements
            if (arr[i] < arr[i + 1])
                swap(arr[i], arr[i + 1]);
        }

        // Flip flag for next pair
        flag = !flag;
    }
}

// Driver Code
int main()
{
    vector<int> arr = {4, 3, 7, 8, 6, 2, 1};
    zigZag(arr);
    for (int x : arr)
        cout << x << " ";

    return 0;
}
C
#include <stdbool.h>
#include <stdio.h>

// Function to convert the given array into zig-zag fashion
// such that a < b > c < d > e...
void zigZag(int *arr, int n)
{
    // Flag indicates expected relation between elements
    // true  -> "<" relation expected
    // false -> ">" relation expected
    bool flag = true;

    // Traverse the array
    for (int i = 0; i <= n - 2; i++)
    {

        // If current relation expected is "<"
        if (flag)
        {
            // If relation is violated, swap elements
            if (arr[i] > arr[i + 1])
            {
                int temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
        // If current relation expected is ">"
        else
        {
            // If relation is violated, swap elements
            if (arr[i] < arr[i + 1])
            {
                int temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }

        // Flip flag for next pair
        flag = !flag;
    }
}

// Driver Code
int main()
{
    int arr[] = {4, 3, 7, 8, 6, 2, 1};
    int n = sizeof(arr) / sizeof(arr[0]);
    zigZag(arr, n);
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}
Java
import java.util.*;

// Function to convert the given array into zig-zag fashion
// such that a < b > c < d > e...
public class GfG {
    static void zigZag(int[] arr)
    {
        // Flag indicates expected relation between elements
        // true  -> "<" relation expected
        // false -> ">" relation expected
        boolean flag = true;

        int n = arr.length;

        // Traverse the array
        for (int i = 0; i <= n - 2; i++) {

            // If current relation expected is "<"
            if (flag) {
                // If relation is violated, swap elements
                if (arr[i] > arr[i + 1]) {
                    int temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                }
            }
            // If current relation expected is ">"
            else {
                // If relation is violated, swap elements
                if (arr[i] < arr[i + 1]) {
                    int temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                }
            }

            // Flip flag for next pair
            flag = !flag;
        }
    }

    public static void main(String[] args)
    {
        int[] arr = { 4, 3, 7, 8, 6, 2, 1 };
        zigZag(arr);
        for (int x : arr)
            System.out.print(x + " ");
    }
}
Python
# Function to convert the given array into zig-zag fashion
# such that a < b > c < d > e...
def zigZag(arr):
    # Flag indicates expected relation between elements
    # true  -> "<" relation expected
    # false -> ">" relation expected
    flag = True

    n = len(arr)

    # Traverse the array
    for i in range(n - 1):
        # If current relation expected is "<"
        if flag:
            # If relation is violated, swap elements
            if arr[i] > arr[i + 1]:
                arr[i], arr[i + 1] = arr[i + 1], arr[i]
        # If current relation expected is ">"
        else:
            # If relation is violated, swap elements
            if arr[i] < arr[i + 1]:
                arr[i], arr[i + 1] = arr[i + 1], arr[i]

        # Flip flag for next pair
        flag = not flag


# Driver Code
arr = [4, 3, 7, 8, 6, 2, 1]
zigZag(arr)
for x in arr:
    print(x, end=' ')
C#
using System;

// Function to convert the given array into zig-zag fashion
// such that a < b > c < d > e...
public class GfG {
    public static void ZigZag(int[] arr)
    {
        // Flag indicates expected relation between elements
        // true  -> "<" relation expected
        // false -> ">" relation expected
        bool flag = true;

        int n = arr.Length;

        // Traverse the array
        for (int i = 0; i <= n - 2; i++) {

            // If current relation expected is "<"
            if (flag) {
                // If relation is violated, swap elements
                if (arr[i] > arr[i + 1]) {
                    int temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                }
            }
            // If current relation expected is ">"
            else {
                // If relation is violated, swap elements
                if (arr[i] < arr[i + 1]) {
                    int temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                }
            }

            // Flip flag for next pair
            flag = !flag;
        }
    }

    public static void Main()
    {
        int[] arr = { 4, 3, 7, 8, 6, 2, 1 };
        ZigZag(arr);
        foreach(int x in arr) Console.Write(x + " ");
    }
}
JavaScript
// Function to convert the given array into zig-zag fashion
// such that a < b > c < d > e...
function zigZag(arr) {
    // Flag indicates expected relation between elements
    // true  -> "<" relation expected
    // false -> ">" relation expected
    let flag = true;

    let n = arr.length;

    // Traverse the array
    for (let i = 0; i <= n - 2; i++) {

        // If current relation expected is "<"
        if (flag) {
            // If relation is violated, swap elements
            if (arr[i] > arr[i + 1]) {
                let temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
        // If current relation expected is ">"
        else {
            // If relation is violated, swap elements
            if (arr[i] < arr[i + 1]) {
                let temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }

        // Flip flag for next pair
        flag =!flag;
    }
}

// Driver Code
let arr = [4, 3, 7, 8, 6, 2, 1];
zigZag(arr);
for (let x of arr)
    process.stdout.write(x + ' ');

Output
3 7 4 8 2 6 1 

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

The Idea is to Rearrange the array in zig-zag form such that arr[0] < arr[1] > arr[2] < arr[3] .... Use a flag to track whether the current relation should be < or >. Traverse the array and check each adjacent pair, swapping if the expected relation is violated. After each step, flip the flag to alternate the condition. This ensures the pattern is formed in a single traversal.

Algorithm:

  • Initialize a boolean variable flag = true to expect a < relation.
  • Start traversing the array from index 0 to n - 2.
  • For each index i, check the relation between arr[i] and arr[i+1].
  • If flag is true, ensure arr[i] < arr[i+1]; if not, swap them.
  • If flag is false, ensure arr[i] > arr[i+1]; if not, swap them.
  • After each step, flip the flag (flag = !flag).
  • Continue this process till the end to get the zig-zag arrangement.

Illustration:

C++
#include <bits/stdc++.h>
using namespace std;

// Zig-Zag conversion
void zigZag(vector<int> &arr)
{
    bool flag = true; // true => "<", false => ">"

    int n = arr.size();

    for (int i = 0; i <= n - 2; i++)
    {
        if (flag)
        {
            if (arr[i] > arr[i + 1])
                swap(arr[i], arr[i + 1]);
        }
        else
        {
            if (arr[i] < arr[i + 1])
                swap(arr[i], arr[i + 1]);
        }
        flag = !flag;
    }
}

int main()
{
    vector<int> arr = {4, 3, 7, 8, 6, 2, 1};

    zigZag(arr);

    for (int x : arr)
        cout << x << " ";

    return 0;
}
C
// C program to sort an array in Zig-Zag form
#include <stdbool.h>
#include <stdio.h>

// This function swaps values pointed by xp and yp
void swap(int *xp, int *yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}

// Program for zig-zag conversion of array
void zigZag(int arr[], int n)
{
    // Flag true indicates relation "<" is expected,
    // else ">" is expected. The first expected relation
    // is "<"
    bool flag = true;

    for (int i = 0; i <= n - 2; i++)
    {
        if (flag) /* "<" relation expected */
        {
            /* If we have a situation like A > B > C,
            we get A > C < B by swapping B and C */
            if (arr[i] > arr[i + 1])
                swap(&arr[i], &arr[i + 1]);
        }
        else /* ">" relation expected */
        {
            /* If we have a situation like A < B < C,
            we get A < C > B by swapping B and C */
            if (arr[i] < arr[i + 1])
                swap(&arr[i], &arr[i + 1]);
        }
        flag = !flag; /* flip flag */
    }
}

// Driver program
int main()
{
    int arr[] = {4, 3, 7, 8, 6, 2, 1};
    int n = sizeof(arr) / sizeof(arr[0]);
    zigZag(arr, n);
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}

// This code is contributed by Sania Kumari Gupta
// (kriSania804)
Java
// Java program to sort an array in Zig-Zag form
import java.util.Arrays;

class Test {
    static int arr[] = new int[] { 4, 3, 7, 8, 6, 2, 1 };

    // Method for zig-zag conversion of array
    static void zigZag()
    {
        // Flag true indicates relation "<" is expected,
        // else ">" is expected. The first expected relation
        // is "<"
        boolean flag = true;

        int temp = 0;

        for (int i = 0; i <= arr.length - 2; i++) {
            if (flag) /* "<" relation expected */
            {
                /* If we have a situation like A > B > C,
                we get A > C < B by swapping B and C */
                if (arr[i] > arr[i + 1]) {
                    // swap
                    temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                }
            }
            else /* ">" relation expected */
            {
                /* If we have a situation like A < B < C,
                we get A < C > B by swapping B and C */
                if (arr[i] < arr[i + 1]) {
                    // swap
                    temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                }
            }
            flag = !flag; /* flip flag */
        }
    }

    // Driver method to test the above function
    public static void main(String[] args)
    {
        zigZag();
        System.out.println(Arrays.toString(arr));
    }
}
Python
# Python program to sort an array in Zig-Zag form

# Program for zig-zag conversion of array


def zigZag(arr, n):
    # Flag true indicates relation "<" is expected,
    # else ">" is expected. The first expected relation
    # is "<"
    flag = True
    for i in range(n - 1):
        # "<" relation expected
        if flag is True:
            # If we have a situation like A > B > C,
            # we get A > C < B
            # by swapping B and C
            if arr[i] > arr[i + 1]:
                arr[i], arr[i + 1] = arr[i + 1], arr[i]
            # ">" relation expected
        else:
            # If we have a situation like A < B < C,
            # we get A < C > B
            # by swapping B and C
            if arr[i] < arr[i + 1]:
                arr[i], arr[i + 1] = arr[i + 1], arr[i]
        flag = bool(1 - flag)
    print(arr)


# Driver program
arr = [4, 3, 7, 8, 6, 2, 1]
n = len(arr)
zigZag(arr, n)

# This code is contributed by Pratik Chhajer
# This code was improved by Hardik Jain
C#
// C# program to sort an array in Zig-Zag form
using System;

class GFG {

    static int[] arr = new int[] { 4, 3, 7, 8, 6, 2, 1 };

    // Method for zig-zag conversion of array
    static void zigZag()
    {

        // Flag true indicates relation "<"
        // is expected, else ">" is expected.
        // The first expected relation
        // is "<"
        bool flag = true;

        int temp = 0;

        for (int i = 0; i <= arr.Length - 2; i++) {

            // "<" relation expected
            if (flag) {

                // If we have a situation like A > B > C,
                // we get A > C < B by swapping B and C
                if (arr[i] > arr[i + 1]) {

                    // Swap
                    temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                }
            }

            // ">" relation expected
            else {

                // If we have a situation like A < B < C,
                // we get A < C > B by swapping B and C
                if (arr[i] < arr[i + 1]) {

                    // Swap
                    temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                }
            }

            // Flip flag
            flag = !flag;
        }
    }

    // Driver code
    public static void Main(String[] args)
    {
        zigZag();
        foreach(int i in arr) Console.Write(i + " ");
    }
}

// This code is contributed by amal kumar choubey
JavaScript
<script>

// JavaScript program to sort an array
// in Zig-Zag form

// Program for zig-zag conversion of array
function zigZag(arr, n)
{
    
    // Flag true indicates relation "<" 
    // is expected, else ">" is expected. 
    // The first expected relation is "<"
    let flag = true;

    for(let i = 0; i <= n - 2; i++)
    {
        
        // "<" relation expected 
        if (flag) 
        {
            
            // If we have a situation like A > B > C,
            // we get A > C < B by swapping B and C 
            if (arr[i] > arr[i + 1])
                temp = arr[i]; 
                arr[i] = arr[i + 1]; 
                arr[i + 1] = temp; 
        }
        
        // ">" relation expected 
        else 
        {
            
            // If we have a situation like A < B < C,
            // we get A < C > B by swapping B and C 
            if (arr[i] < arr[i + 1])
                 temp = arr[i]; 
                 arr[i] = arr[i + 1]; 
                 arr[i + 1] = temp; 
        }
        
        // Flip flag 
        flag = !flag; 
    }
}

// Driver code
let arr = [ 4, 3, 7, 8, 6, 2, 1 ];
let n = arr.length;
zigZag(arr, n);

for(let i = 0; i < n; i++)
    document.write(arr[i] + " ");

// This code is contributed by Surbhi Tyagi.

</script>

Output
3 7 4 8 2 6 1 
Comment