August 13, 2022

Given an integer array we have to find the wave of array and print the result on screen.

so what is wave of array?

when we have to find print the array in arr[0] >= arr[1] <= arr[2] >= arr[3] form then that array is wave array.

Example:

Input:7 6 4 5 0 1
output:1 0 5 4 7 6 

Logic:

step 1- sort the array
step 2-swap their adjacent element.
step 3-print the resultant array.

code:

#include<bits/stdc++.h>
using namespace std;
int main() 
{ 
    int n;
    cin>>n;
	int a[n];
	for(int i=0;i<n;i++)
	{
	    cin>>a[i];
	}
	sort(a, a+n); 
	for (int i=0; i<n-1; i+= 2) 
	{
	   swap(a[i],a[i+1]); 
	}
	for (int i=0; i<n; i++) 
	{
	cout<<a[i]<<" "; 
	}
	cout<<endl;
} 

Output:

6
 7 6 4 5 0 1

1 0 5 4 7 6 

Time Complexity:O(Nlogn)

Space Complexity:O(1)

Leave a Reply

Your email address will not be published.