RUN


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. Sort the array using sort() function.
  3. Elements are swapped to get the array in wave form.

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;
}

Report Error/ Suggestion

Related Posts:




CopyRight © 2020

CopyRight © 2020