Array ( [0] => [1] => questions [2] => Strings [3] => Wave-Array )
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.)
First line contains the size of the first array. Next line contains the m integers separated by the spaces.
Print the array of elements as show in above order.
6 6 1 3 8 4 9
3 1 6 4 9 8
5 9 1 6 3 6
3 1 6 6 9
8 4 1 11 5 8 9 7 10
4 1 7 5 9 8 11 10
Login to see Discussion
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.
Login to see Solution