Array ( [0] => [1] => questions [2] => Arrays [3] => Wave-Array ) Arrays | Wave Array | THE INQUISITIVE





Wave Array

LEVEL:Beginner

Description

Given an array of integers. You have to sort the array into a wave like array and return it. (arrange the element into a sequence such that a1>=a2<=a3>=a4<=a5----etc.)

Input Format

First line contains the size of the first array. Next line contains the m integers separated by the spaces.

Output Format

Print the array of elements as show in above order.


Example 1:

Input
6
6 1 3 8 4 9
Output
3 1 6 4 9 8 
Example 2:

Input
5
9 1 6 3 6
Output
3 1 6 6 9
Example 3:

Input
8 
4 1 11 5 8 9 7 10
Output
4 1 7 5 9 8 11 10

oops

Login to see Discussion




Approach

Approach1: Sort

Step-i) Sort the given array.
Step-ii) Swap first and the second element, then swap the 3rd and 4th elements.
Step-iii) Swap i and i+1 elements until n.
Step-iv) Return the final array.

Time Complexity: O(n logn)
Space Complexity: O(n)

Approach2:

Step-i) Take an array of size maximum element of the given array.
Step-ii) Iterate through the array and increment its indexes as per the given numbers.
Step-iii) Traverse from starting until second 1, once we reach the 2nd one make it as zero and print the index.
Step-iv) Now traverse back to find next one. Make it as zero and traverse front to get next second one.
Step-v) Repeat this process until all ones in the array are completed.

Time Complexity: O(n)
Space Complexity: O(n)


Note :

Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.

oops

Login to see Solution