Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Convert Array into Zig-Zag fashion
Next article icon

Convert Array into Zig-Zag fashion

Last Updated : 19 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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]

Table of Content

  • [Naive Approach] Using Sorting - O(N*log(N)) time and O(1) Space
  • [Expected Approach] Rearranging Triplets using Flag - O(N) time and O(1) Space

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

C++
#include <bits/stdc++.h> using namespace std;  void zigZag(vector<int>& arr, int N) {     // sort the array by using the sort function     sort(arr.begin(), arr.end());     // traverse the array from 1 to N -1     for (int i = 1; i < N - 1; i += 2) {         // swap the current element with the next element         swap(arr[i], arr[i + 1]);     }     // print the complete array     for (int i = 0; i < N; i++) {         cout << arr[i] << " ";     }     return; } int main() {     vector<int> arr = { 4, 3, 7, 8, 6, 2, 1 };     int N = 7;     zigZag(arr, N);     return 0; } 
C
#include <stdio.h> #include <stdlib.h> int comparator(const void* p, const void* q) {     return (*(int*)p - *(int*)q); } void zigZag(int arr[], int N) {     // sort the array using the qsort function     qsort((void*)arr, N, sizeof(arr[0]), comparator);     for (int i = 1; i < N - 1; i += 2) {         // swap the value of current element with next         // element         int temp = arr[i];         arr[i] = arr[i + 1];         arr[i + 1] = temp;     }     // print the complete array     for (int i = 0; i < N; i++)         printf("%d ", arr[i]);     return; } int main() {     int arr[] = { 2, 3, 4, 1, 5, 7, 6 };     int N = 7;     zigZag(arr, N);     return 0; } 
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 };     static void zigZag()     {         // sort the array using the sort function         Arrays.sort(arr);         // traverse the array from 1 to N -1         for (int i = 1; i <= arr.length - 2; i += 2) {             // swap the current element with the next             // element             int temp = arr[i];             arr[i] = arr[i + 1];             arr[i + 1] = temp;         }     }      // Driver method to test the above function     public static void main(String[] args)     {         zigZag();         // print the complete array         System.out.println(Arrays.toString(arr));     } } 
Python
def zigZag(arr, n):     # use sort function to sort the array     arr.sort()     # traverse the array from 1 to n-1     for i in range(1, n-1, 2):       # swap value of current element with next element         arr[i], arr[i+1] = arr[i+1], arr[i]     # print the array     print(arr)   # Driver program if __name__ == "__main__":     arr = [4, 3, 7, 8, 6, 2, 1]     n = len(arr)     zigZag(arr, n) 
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()     {         // sort the array by using the sort function         Array.Sort(arr);         for (int i = 1; i <= arr.Length - 2; i += 2) {             // swap the current element with next next             // element             int temp = arr[i];             arr[i] = arr[i + 1];             arr[i + 1] = temp;         }     }      // Driver code     public static void Main(String[] args)     {         zigZag();         // print the array         foreach(int i in arr) Console.Write(i + " ");     } } 
JavaScript
<script>  // JavaScript program to sort an array // in Zig-Zag form  // Program for zig-zag conversion of array function zigZag(arr, n) {     // sort the by using the sort function     arr.sort();     //traverse the array from 1 to n-1     for(let i = 1; i <= n - 2; i++)     {     // swap the current element with next element         let temp = arr[i];         arr[i] = arr[i+1];         arr[i+1] = temp;     } }  // Driver code let arr = [ 4, 3, 7, 8, 6, 2, 1 ]; let n = arr.length; zigZag(arr, n); // print the array for(let i = 0; i < n; i++)     document.write(arr[i] + " ");  // This code is contributed by Surbhi Tyagi.  </script> 

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:

C++
// C++ program to sort an array in Zig-Zag form #include <iostream> using namespace std;  // 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++)         cout << arr[i] << " ";     return 0; }  // This code is contributed by Sania Kumari Gupta // (kriSania804) 
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 

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

Illustration of the Expected Approach:



Next Article
Convert Array into Zig-Zag fashion

K

kartik
Improve
Article Tags :
  • DSA
  • Arrays
  • Amazon
  • Paytm
  • array-rearrange
Practice Tags :
  • Amazon
  • Paytm
  • Arrays

Similar Reads

    Converting an array of integers into Zig-Zag fashion!
    Let us elaborate the problem a little more. Basically, we are given an array of integers and we need to arrange this array in an order such that 1st element is lesser than 2nd element, 2nd element is greater than 3rd element, 3rd element is lesser than 4th element, 4th element is greater than 5th el
    4 min read
    Javascript Program For Converting Array Into Zig-Zag Fashion
    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[
    3 min read
    Print matrix in zig-zag fashion
    Given a matrix of 2D array of n rows and m columns. Print this matrix in ZIG-ZAG fashion as shown in figure. Example: Input: {{1, 2, 3}{4, 5, 6}{7, 8, 9}}Output: 1 2 4 7 5 3 6 8 9Input : [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]Output:: 1 2 5 9 6 3 4 7 10 13 14 11 8 12 15 16Thi
    10 min read
    Rearrange a Linked List in Zig-Zag fashion
    Given a linked list, rearrange it such that the converted list should be of the form a < b > c < d > e < f … where a, b, c… are consecutive data nodes of the linked list. Examples: Input: 1->2->3->4 Output: 1->3->2->4 Explanation : 1 and 3 should come first before 2
    15+ min read
    Print matrix in zig-zag fashion from the last column
    Given a matrix of 2-Dimensional array of n rows and n columns. Print this matrix in ZIG-ZAG fashion starting from column n-1 as shown in the figure below. Examples: Input: mat[][] = 1 2 3 4 5 6 7 8 9 Output: 3 2 6 9 5 1 4 8 7 Input: mat[][] = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 4 3 8 12 7
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences