Program to sort a given unsorted array in wave form in C++

C++ program to sort a given unsorted array of integers, in a waveform

Given:  An unsorted array of integers, we have to sort the array into a wave-like array. 

An array array[0….n-1] is sorted in wave form if array[0] >= array[1] <= array[2] >= array[3] <= array[4] >= array[5]…

Example:

Input: {4, 12, 15, 2, 20, 30, 21}

Output: {4 2 15 12 21 20 30}

# Algorithm

  1. Take an array input.
  2. Check if the array is empty or has only one element. If so, return the array as it is.
  3. Sort the array using the sort() function.
  4. Iterate through the array in pairs (i.e., with a step size of 2). For each pair, swap the elements if the first element is larger than the second element.
  5. Print the modified array.

Code:

#include <iostream>
#include <algorithm>

using namespace std;

void swap(int* p, int* q) {
  int temp = *p;
  *p = *q;
  *q = temp;
}

void array_in_wave(int array[], int n) {
  sort(array, array + n);
  for (int i = 0; i < n - 1; i += 2)
    swap(&array[i], &array[i + 1]);
}

int main() {
  int array[100], n, i;
  cout << "Enter number of elements: ";
  cin >> n;
  cout << "\nEnter elements: ";

  for (i = 0; i < n; i++)
    cin >> array[i];

  cout << "Original array: ";

  for (int i = 0; i < n; i++)
    cout << array[i] << " ";

  array_in_wave(array, n);

  cout << "\nWave form of the array is: ";

  for (int i = 0; i < n; i++)
    cout << array[i] << " ";

  return 0;
}

Output

Original array: 1 2 3 4 5
Wave form of the array is: 2 1 4 3 5
Program to sort a given unsorted array in wave form in C++