Convert array into Zig-Zag fashion - GeeksforGeeks

05 May, 2022
Given an array of DISTINCT elements, rearrange the elements of array in zig-zag fashion in O(n) time. The converted array should be in form a < b > c < d > e < f. 
Example:
Input: arr[] = {4, 3, 7, 8, 6, 2, 1} Output: arr[] = {3, 7, 4, 8, 2, 6, 1}
Input: arr[] = {1, 4, 3, 2} Output: arr[] = {1, 4, 2, 3}
A Simple Solution is to first sort the array. After sorting, exclude the first element, swap the remaining elements in pairs. (i.e. keep arr[0] as it is, swap arr[1] and arr[2], swap arr[3] and arr[4], and so on). Time complexity: O(N log N) since we need to sort the array first.
We can convert in O(n) time using an efficient approach. The idea is to use a modified one pass of bubble sort.
Maintain a flag for representing which order(i.e. < or >) currently we need.
If the current two elements are not in that order then swap those elements otherwise not.
Let us see the main logic using three consecutive elements A, B, C.
Suppose we are processing B and C currently and the current relation is ‘<‘, but we have B > C. Since current relation is ‘<‘ previous relation must be ‘>’ i.e., A must be greater than B. So, the relation is A > B and B > C. We can deduce A > C. So if we swap B and C then the relation is A > C and C < B. Finally we get the desired order A C B Refer this for more explanation.
Below image is a dry run of the above approach:
Below is the implementation of above approach:
C++
Java
Python
C#
Javascript
// C++ program to sort an array in Zig-Zag form#include <iostream>using namespace std; // Program for zig-zag conversion of arrayvoid 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 programint 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++)        cout << arr[i] << " ";    return 0;}
// Java program to sort an array in Zig-Zag formimport 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 program to sort an array in Zig-Zag form # Program for zig-zag conversion of arraydef 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 programarr = [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# program to sort an array in Zig-Zag formusing System; class GFG{     static int []arr = new int[]{ 4, 3, 7, 8, 6, 2, 1 }; // Method for zig-zag conversion of arraystatic 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 codepublic static void Main(String[] args){    zigZag();    foreach(int i in arr)        Console.Write(i + " ");}} // This code is contributed by amal kumar choubey
<script> // JavaScript program to sort an array// in Zig-Zag form // Program for zig-zag conversion of arrayfunction 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 codelet 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>
3 7 4 8 2 6 1 
Time complexity: O(n) Auxiliary Space: O(1) 
Another approach:Since the relation needed is a<b>c<d>e<f, it means the odd position elements have to be greater than its adjacent i.e. the even position elements. Simply traverse the array at the odd positions and check if it is greater than its adjacent elements, if it is not then swap them.
Follow the steps below to implement the above idea:
Java
/*package whatever //do not write package name here */ import java.io.*;import java.util.*;class GFG {     // Method for zig-zag conversion of array    static void swap(int a[], int i, int j)    {        int temp = a[i];        a[i] = a[j];        a[j] = temp;    }     static void zigZag(int a[], int n)    {        for (int i = 1; i < n; i += 2) {            // Check if previous element           // is greater then the current element           // then swap them            if (a[i - 1] > a[i])                swap(a, i, i - 1);                       // if next element is greater then            // then the current element then            // also swap them.            if (i + 1 < n && (a[i + 1] > a[i]))                swap(a, i, i + 1);        }    }     // Driver Code    public static void main(String[] args)    {        int a[] = new int[] { 4, 3, 7, 8, 6, 2, 1 };        zigZag(a, a.length);        System.out.println(Arrays.toString(a));    }}
[3, 7, 4, 8, 2, 6, 1]

Time complexity: O(n) Auxiliary Space: O(1)  
YouTubeGeeksforGeeks507K subscribersConvert array into Zig-Zag fashion | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:53•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fYR0X_MP4Ks" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Siva Krishna Aleti. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
Amal Kumar Choubey
surbhityagi15
hdkjain
patelkhananandini
Amazon
Paytm
Arrays
Paytm
Amazon
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Python | Using 2D arrays/lists the right way
Array of Strings in C++ (5 Different Ways to Create)