Sort an array in wave form

23 Jun, 2022
Given an unsorted array of integers, sort the array into a wave like array. An array ‘arr[0..n-1]’ is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= .....
what is a wave array?
well, you have seen waves right? how do they look? if you will form a graph of them it would be some in some up-down fashion.
that is what you have to do here, you are supposed to arrange numbers in such a way that if we will form a graph it will be in an up-down fashion rather than a straight line.
Examples: 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
 Input:  arr[] = {10, 5, 6, 3, 2, 20, 100, 80}
 Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80} OR
                 {20, 5, 10, 2, 80, 6, 100, 3} OR
                 any other array that is in wave form
                 
                 here you can see {10, 5, 6, 2, 20, 3, 100, 80} first element is larger than the second and the same
                 thing is repeated again and again. large element - small element-large element -small element
                 and so on .
                 it can be small element-larger element - small element-large element -small element too.
                 all you need to maintain is the up-down fashion which represents a wave.
                  there can be multiple answers.
                 

 Input:  arr[] = {20, 10, 8, 6, 4, 2}
 Output: arr[] = {20, 8, 10, 4, 6, 2} OR
                 {10, 8, 20, 2, 6, 4} OR
                 any other array that is in wave form

 Input:  arr[] = {2, 4, 6, 8, 10, 20}
 Output: arr[] = {4, 2, 8, 6, 20, 10} OR
                 any other array that is in wave form

 Input:  arr[] = {3, 6, 5, 10, 7, 20}
 Output: arr[] = {6, 3, 10, 5, 20, 7} OR
                 any other array that is in wave form
 
A Simple Solution is to use sorting. First sort the input array, then swap all adjacent elements.For example, let the input array be {3, 6, 5, 10, 7, 20}. After sorting, we get {3, 5, 6, 7, 10, 20}. After swapping adjacent elements, we get {5, 3, 7, 6, 20, 10}. 
Below is implementation of the above idea. 
C++
Java
Python3
C#
Javascript
// A C++ program to sort an array in wave form using// a sorting function#include<iostream>#include<algorithm>using namespace std; // A utility method to swap two numbers.void swap(int *x, int *y){    int temp = *x;    *x = *y;    *y = temp;} // This function sorts arr[0..n-1] in wave form, i.e.,// arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5]..void sortInWave(int arr[], int n){    // Sort the input array    sort(arr, arr+n);     // Swap adjacent elements    for (int i=0; i<n-1; i += 2)        swap(&arr[i], &arr[i+1]);} // Driver program to test above functionint main(){    int arr[] = {10, 90, 49, 2, 1, 5, 23};    int n = sizeof(arr)/sizeof(arr[0]);    sortInWave(arr, n);    for (int i=0; i<n; i++)       cout << arr[i] << " ";    return 0;}
// Java implementation of naive method for sorting// an array in wave form.import java.util.*; class SortWave{    // A utility method to swap two numbers.    void swap(int arr[], int a, int b)    {        int temp = arr[a];        arr[a] = arr[b];        arr[b] = temp;    }     // This function sorts arr[0..n-1] in wave form, i.e.,    // arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4]..    void sortInWave(int arr[], int n)    {        // Sort the input array        Arrays.sort(arr);         // Swap adjacent elements        for (int i=0; i<n-1; i += 2)            swap(arr, i, i+1);    }     // Driver method    public static void main(String args[])    {        SortWave ob = new SortWave();        int arr[] = {10, 90, 49, 2, 1, 5, 23};        int n = arr.length;        ob.sortInWave(arr, n);        for (int i : arr)            System.out.print(i + " ");    }}/*This code is contributed by Rajat Mishra*/
# Python function to sort the array arr[0..n-1] in wave form,# i.e., arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5]def sortInWave(arr, n):         #sort the array    arr.sort()        # Swap adjacent elements    for i in range(0,n-1,2):        arr[i], arr[i+1] = arr[i+1], arr[i] # Driver programarr = [10, 90, 49, 2, 1, 5, 23]sortInWave(arr, len(arr))for i in range(0,len(arr)):    print (arr[i],end=" ")     # This code is contributed by __Devesh Agrawal__
// C# implementation of naive method// for sorting an array in wave form.using System; class SortWave {         // A utility method to swap two numbers.    void swap(int[] arr, int a, int b)    {        int temp = arr[a];        arr[a] = arr[b];        arr[b] = temp;    }     // This function sorts arr[0..n-1] in wave form, i.e.,    // arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4]..    void sortInWave(int[] arr, int n)    {        // Sort the input array        Array.Sort(arr);         // Swap adjacent elements        for (int i = 0; i < n - 1; i += 2)            swap(arr, i, i + 1);    }     // Driver method    public static void Main()    {        SortWave ob = new SortWave();        int[] arr = { 10, 90, 49, 2, 1, 5, 23 };        int n = arr.Length;                 ob.sortInWave(arr, n);        for (int i = 0; i < n; i++)        Console.Write(arr[i] + " ");    }} // This code is contributed by vt_m.
<script> // A JavaScript program to sort an array// in wave form using a sorting function // A utility method to swap two numbers.function swap(arr, x, y){    let temp = arr[x];    arr[x] = arr[y];    arr[y] = temp} // This function sorts arr[0..n-1] in// wave form, i.e.,// arr[0] >= arr[1] <= arr[2] >=// arr[3] <= arr[4] >= arr[5]..function sortInWave(arr, n){         // Sort the input array    arr.sort((a, b) => a - b);     // Swap adjacent elements    for(let i = 0; i < n - 1; i += 2)        swap(arr, i, i + 1);} // Driver codelet arr = [ 10, 90, 49, 2, 1, 5, 23 ];let n = arr.length; sortInWave(arr, n); for(let i = 0; i < n; i++)    document.write(arr[i] + " "); // This code is contributed by Surbhi Tyagi. </script>
Output: 
2 1 10 5 49 23 90
Time Complexity: O(nlogn)
Auxiliary Space: O(1)The time complexity of the above solution is O(nLogn) if an O(nLogn) sorting algorithm like Merge Sort, Heap Sort, etc are used.This can be done in O(n) time by doing a single traversal of the given array. The idea is based on the fact that if we make sure that all even positioned (at index 0, 2, 4, ..) elements are greater than their adjacent odd elements, we don’t need to worry about oddly positioned elements. 
The following are simple steps. 1) Traverse all even positioned elements of the input array, and do the following. ....a) If the current element is smaller than the previous odd element, swap previous and current. ....b) If the current element is smaller than the next odd element, swap next and current.
Below is implementation of the above idea.  
C++14
Java
Python3
C#
Javascript
// A O(n) program to sort an input array in wave form#include<iostream>using namespace std; // A utility method to swap two numbers.void swap(int *x, int *y){    int temp = *x;    *x = *y;    *y = temp;} // This function sorts arr[0..n-1] in wave form, i.e., arr[0] >=// arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5] ....void sortInWave(int arr[], int n){    // Traverse all even elements    for (int i = 0; i < n; i+=2)    {        // If current even element is smaller than previous        if (i>0 && arr[i-1] > arr[i] )            swap(&arr[i], &arr[i-1]);         // If current even element is smaller than next        if (i<n-1 && arr[i] < arr[i+1] )            swap(&arr[i], &arr[i + 1]);    }} // Driver program to test above functionint main(){    int arr[] = {10, 90, 49, 2, 1, 5, 23};    int n = sizeof(arr)/sizeof(arr[0]);    sortInWave(arr, n);    for (int i=0; i<n; i++)       cout << arr[i] << " ";    return 0;}
// A O(n) Java program to sort an input array in wave formclass SortWave{    // A utility method to swap two numbers.    void swap(int arr[], int a, int b)    {        int temp = arr[a];        arr[a] = arr[b];        arr[b] = temp;    }     // This function sorts arr[0..n-1] in wave form, i.e.,    // arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4]....    void sortInWave(int arr[], int n)    {        // Traverse all even elements        for(int i = 0; i < n-1; i+=2){            //swap odd and even positions            swap(arr, i, i+1);        }    }     // Driver program to test above function    public static void main(String args[])    {        SortWave ob = new SortWave();        int arr[] = {10, 90, 49, 2, 1, 5, 23};        int n = arr.length;        ob.sortInWave(arr, n);        for (int i : arr)            System.out.print(i+" ");    }}/*This code is contributed by Rajat Mishra*/
# Python function to sort the array arr[0..n-1] in wave form,# i.e., arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5]def sortInWave(arr, n):         # Traverse all even elements    for i in range(0, n, 2):                 # If current even element is smaller than previous        if (i> 0 and arr[i] < arr[i-1]):            arr[i],arr[i-1] = arr[i-1],arr[i]                 # If current even element is smaller than next        if (i < n-1 and arr[i] < arr[i+1]):            arr[i],arr[i+1] = arr[i+1],arr[i] # Driver programarr = [10, 90, 49, 2, 1, 5, 23]sortInWave(arr, len(arr))for i in range(0,len(arr)):    print (arr[i],end=" ")     # This code is contributed by __Devesh Agrawal__
// A O(n) C# program to sort an// input array in wave formusing System; class SortWave {         // A utility method to swap two numbers.    void swap(int[] arr, int a, int b)    {        int temp = arr[a];        arr[a] = arr[b];        arr[b] = temp;    }     // This function sorts arr[0..n-1] in wave form, i.e.,    // arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4]....    void sortInWave(int[] arr, int n)    {        // Traverse all even elements        for (int i = 0; i < n; i += 2) {                         // If current even element is smaller            // than previous            if (i > 0 && arr[i - 1] > arr[i])                swap(arr, i - 1, i);             // If current even element is smaller            // than next            if (i < n - 1 && arr[i] < arr[i + 1])                swap(arr, i, i + 1);        }    }     // Driver program to test above function    public static void Main()    {        SortWave ob = new SortWave();        int[] arr = { 10, 90, 49, 2, 1, 5, 23 };        int n = arr.Length;                 ob.sortInWave(arr, n);        for (int i = 0; i < n; i++)        Console.Write(arr[i] + " ");    }} // This code is contributed by vt_m.
<script> // A O(n) program to sort// an input array in wave form // A utility method to swap two numbers.function swap(arr, a, b)    {        let temp = arr[a];        arr[a] = arr[b];        arr[b] = temp;    }       // This function sorts arr[0..n-1]    // in wave form, i.e.,    // arr[0] >= arr[1] <= arr[2] >=    // arr[3] <= arr[4]....function sortInWave( arr, n)    {        // Traverse all even elements        for (let i = 0; i < n; i+=2)        {            // If current even element            // is smaller than previous            if (i>0 && arr[i-1] > arr[i] )                swap(arr, i-1, i);               // If current even element            // is smaller than next            if (i<n-1 && arr[i] < arr[i+1] )                swap(arr, i, i + 1);        }    }     // driver code         let arr = [10, 90, 49, 2, 1, 5, 23];    let n = arr.length;    sortInWave(arr, n);    for (let i=0; i<n; i++)      document.write(arr[i] + " ");     </script>
Output: 
90 10 49 1 5 2 23
Time Complexity: O(n)
Auxiliary Space: O(1)
Sort an array in wave form | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersSort an array in wave form | 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 / 4:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=8oR5OBW5buk" 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 Shivam. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. 
nidhi_biet
jana_sayantan
surbhityagi15
amartyaghoshgfg
sweta_thakur
dharm_kumar
srinivasalujuldi
tarakki100
avinashdhinwa
array-rearrange
FactSet
Zoho
Arrays
Sorting
Zoho
FactSet
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.