Java Program to Sort an array in wave form
Last Updated :
09 Dec, 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] >= .....
Examples:
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
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 are implementations of this simple approach.
Java
// 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*/
Time complexity: O(n Log n), if a O(nLogn) sorting algorithm like Merge Sort, Heap Sort, .. etc is used.
Auxiliary Space: O(1)
Another approach:
This can be done in O(n) time by doing a single traversal of 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 odd positioned elements.
The following are simple steps.
- Traverse all even positioned elements of input array, and do following.
- If current element is smaller than previous odd element, swap previous and current.
- If current element is smaller than next odd element, swap next and current.
Below are implementations of the above simple algorithm.
Java
// A O(n) Java program to sort an input 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)
{
// 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(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*/
Time complexity: O(n)
Auxiliary space: O(1)
Please refer complete article on Sort an array in wave form for more details!
Similar Reads
Java Program to Sort 2D Array Across Columns
The Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. It is found in the java.util package and implements the List interface, so we can use all the methods of List interface here. This program is used to Sor
3 min read
Java Program to Sort Items By Weight
Given two array items and weights which denotes items and their respective weights. Both arrays are of equal length. For every index 'i', items[i] and weights[i] represent the ith item name and its weight respectively. Your task is to return a new array of items sorted in decreasing order by their w
3 min read
Java Program to Sort 2D Array Across Left Diagonal
The Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. It is found in java.util package and implements the List interface, so we can use all the methods of List interface here. This program is used to Sort th
3 min read
Java Program for Check if an array is sorted and rotated
Given an array of N distinct integers. The task is to write a program to check if this array is sorted and rotated counter-clockwise. A sorted array is not considered as sorted and rotated, i.e., there should at least one rotation.Examples: Input : arr[] = { 3, 4, 5, 1, 2 } Output : YES The above ar
3 min read
Java Program to Print the Smallest Element in an Array
Java provides a data structure, the array, which stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type. Example: arr1[] = {2 , -1 , 9 , 10} output : -1 arr2[] = {0, -10, -13, 5} output : -13 We need to find and print the smallest value
3 min read
Java Program For Sorting An Array Of 0s, 1s and 2s
Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last.Examples: Input: {0, 1, 2, 0, 1, 2} Output: {0, 0, 1, 1, 2, 2} Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1} Output: {0, 0, 0,
6 min read
Java Program to Sort Objects in ArrayList by Date
The foremost tool that strikes is the sort() method to be used for the comparator mechanism of the Collections class which sorts in the decreasing order. Yes if in generic we want to achieve the goal considering the boundary condition where objects to sorted are user-defined then blindly do with Com
6 min read
Java Program to Print the Elements of an Array
An array is a data structure that stores a collection of like-typed variables in contiguous memory allocation. Once created, the size of an array in Java cannot be changed. It's important to note that arrays in Java function differently than they do in C/C++As you see, the array of size 9 holds elem
6 min read
Program to convert Primitive Array to Stream in Java
An array is a group of like-typed variables that are referred to by a common name. An array can contain primitives data types as well as objects of a class depending on the definition of the array. In case of primitives data types, the actual values are stored in contiguous memory locations. In case
3 min read
Java Program for Bitonic Sort
Bitonic Sequence: A sequence is called Bitonic if it is first increasing, then decreasing. In other words, an array arr[0..n-i] is Bitonic if there exists an index i where 0<=i<=n-1 such that x0 <= x1 â¦..<= xi and xi >= xi+1â¦.. >= xn-1 A sequence, sorted in increasing order is cons
4 min read