Sort an array in wave form
Last Updated :
27 Jun, 2025
Given an sorted array arr[] of integers, rearrange the elements into a wave-like array. An array arr[0..n-1]
is said to be in wave form if it follows the pattern: \scriptsize arr[0] \geq arr[1] \leq arr[2] \geq arr[3] \leq arr[4] \geq \dots and so on and find the lexicographically smallest one.
Note: The given array is sorted in ascending order, and modify the given array in-place without returning a new array.
Input: arr[] = [1, 2, 3, 4, 5]
Output: [2, 1, 4, 3, 5]
Explanation: Array elements after sorting it in the waveform are 2, 1, 4, 3, 5.
Input: arr[] = [2, 4, 7, 8, 9, 10]
Output: [4, 2, 8, 7, 10, 9]
Explanation: Array elements after sorting it in the waveform are 4, 2, 8, 7, 10, 9.
Approach:
The main idea of this approach is to rearrange it into a wave form by swapping adjacent elements in pairs.
Since, the elements are in increasing order. Then, by swapping every pair of adjacent elements (i.e., arr[0]
with arr[1]
, arr[2]
with arr[3]
, and so on), we create a pattern where:
- Every even index
i
holds a value greater than or equal to its neighboring odd indices i - 1
and i + 1
(if they exist). - This guarantees the wave condition:
arr[0] >= arr[1] <= arr[2] >= arr[3] <= ...
The sorted array ensures the numbers are close enough to form valid wave peaks and valleys, and the pairwise swaps are what enforce the pattern.
C++
#include<iostream>
#include<vector>
#include <algorithm>
using namespace std;
void sortInWave(vector<int> &arr){
int n = arr.size();
// Swap adjacent elements to create wave pattern
for (int i = 0; i < n - 1; i += 2) {
swap(arr[i], arr[i + 1]);
}
}
// Driver program to test above function
int main(){
vector<int> arr = {1, 2, 3, 4, 5};
sortInWave(arr);
for (int i=0; i<arr.size(); i++)
cout << arr[i] << " ";
return 0;
}
C
#include<stdio.h>
#include<stdlib.h>
void swap(int *x, int *y){
int temp = *x;
*x = *y;
*y = temp;
}
void sortInWave(int arr[], int n){
// Swap adjacent elements
for (int i=0; i<n-1; i += 2)
swap(&arr[i], &arr[i+1]);
}
// Driver Code
int main(){
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
sortInWave(arr, n);
for (int i=0; i<n; i++)
printf("%d ",arr[i]);
return 0;
}
Java
import java.util.*;
class GfG{
void sortInWave(int arr[]){
int n = arr.length;
// Swap adjacent elements
for (int i=0; i<n-1; i += 2){
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
// Driver method
public static void main(String args[]){
GfG ob = new GfG();
int arr[] = {1, 2, 3, 4, 5};
ob.sortInWave(arr);
for (int i : arr)
System.out.print(i + " ");
}
}
Python
def sortInWave(arr):
n = len(arr)
# Swap adjacent elements
for i in range(0,n-1,2):
arr[i], arr[i+1] = arr[i+1], arr[i]
# Driver program
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5]
sortInWave(arr)
for i in range(0,len(arr)):
print (arr[i],end=" ")
C#
using System;
class GfG{
// 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
void sortInWave(int[] arr){
int n = arr.Length;
// Swap adjacent elements
for (int i = 0; i < n - 1; i += 2)
swap(arr, i, i + 1);
}
// Driver method
public static void Main(){
GfG ob = new GfG();
int[] arr = {1, 2, 3, 4, 5};
int n = arr.Length;
ob.sortInWave(arr);
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
}
JavaScript
// Utility function to swap two elements
function swap(arr, x, y) {
let temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
function sortInWave(arr) {
// Swap adjacent elements
for (let i = 0; i < arr.length - 1; i += 2) {
swap(arr, i, i + 1);
}
}
// Driver code
let arr = [1, 2, 3, 4, 5];
sortInWave(arr);
console.log(arr.join(" "));
Time Complexity: O(n), a single pass swaps adjacent pairs.
Auxiliary Space: O(1), in-place swaps use no extra storage.
Similar Reads
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to Sorting Techniques â Data Structure and Algorithm Tutorials Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. Why Sorting Algorithms are ImportantThe sorting algorithm is important in Com
3 min read
Most Common Sorting Algorithms
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Heap Sort - Data Structures and Algorithms Tutorials Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
14 min read
Counting Sort - Data Structures and Algorithms Tutorials Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
9 min read