Sort an Array in Wave Form

You are given an unsorted array ARR. Your task is to sort it so that it forms a wave-like array.

Input:

The first line contains an integer 'T', the number of test cases.
For each test case,
The first line contains a single integer 'N', the number of elements in the array.
The second line contains 'N' space-separated integers representing 'ARR'.

Output:

For each test case, output a single line with space-separated integers corresponding to the elements of a wave array.

Example:

If the given sequence ARR has N elements, it should follow the wave pattern:

ARR[0] >= ARR[1] and ARR[1] <= ARR[2]
ARR[2] >= ARR[3] and ARR[3] <= ARR[4]

For instance, ARR = { 4, 3, 5, 2, 3, 1, 2 } can be reorganized into a wave because:

4 > 3, 3 < 5
5 > 2, 2 < 3
3 > 1, 1 < 2

Constraints:

  • 1 <= T <= 50
  • 1 <= N <= 10^4
  • -10^9 <= ARR[i] <= 10^9
  • Time limit: 1 second
Note:
  • The first element ARR[0] should be greater than or equal to ARR[1].
  • There can be multiple valid wave arrays, return any one.
  • Only implement the function, the output is automatically handled.
AnswerBot
7d

Sort an array in a wave-like pattern where each element is greater than or equal to its adjacent elements.

  • Iterate through the array and swap elements at even indices with their adjacent odd indices to...read more

Help your peers!
Add answer anonymously...
Clearwater Analytics Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter