Thursday, June 24, 2021
Home coding Write a program to find the wave array.

Write a program to find the wave array.

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

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments