Examples :
Input: arr[ ] = {20, 10, 8, 6, 4, 2}
Output: arr[ ] = {20, 8, 10, 4, 6, 2}
#include <iostream>
#include <algorithm>
using namespace std;
// function to swap two elements
// of the array
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
// function to sort the array
// in wave form
void sortWave(int array[], int n)
{
// Sort the input array
sort(array, array + n);
// iterate through the array
for (int i = 0; i < n - 1; i += 2)
// swap adjacent array
swap(&array[i], &array[i + 1]);
}
// Function to print the array
void printArray(int array[], int n)
{
for (int i = 0; i < n; i++)
cout << array[i] << " ";
}
// main function
int main()
{
int array[] = {10, 90, 49, 2, 1, 5, 23};
int n = sizeof(array) / sizeof(array[0]);
sortWave(array, n);
printArray(array, n);
return 0;
}
Output:
2 1 10 5 49 23 90
0 Comments