Show problems as
Classic problem #324MediumArrayDivide and ConquerGreedySortingQuickselect

Wiggle Sort II

Real-world version: Laying the Readings Out in a Zigzag
Tracked in this browser only
Read Wiggle Sort II on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstSorting · Arrays, animated step by step

A row holds the readings readings. A zigzag is an arrangement of them where the first is below the second, the second is above the third, the third is below the fourth, and so on, strictly alternating all the way along.

Several zigzags may be possible, so the one wanted is pinned down like this. Put the readings in non-decreasing order and cut them into a lower part holding the first half, rounded up when the count is odd, and an upper part holding the rest. Fill positions 0, 2, 4 and onwards from the lower part taken back to front, and positions 1, 3, 5 and onwards from the upper part taken back to front.

Return that arrangement. The readings always allow a zigzag.

Examples

Example 1

Input
readings = [1, 2, 3]
Output
[2, 3, 1]

In order the readings are 1, 2 and 3. The lower part holds 1 and 2 and the upper part holds 3, and taking each from the back gives 2, then 3, then 1.

Example 2

Input
readings = [1, 1, 2]
Output
[1, 2, 1]

The lower part holds the two 1 readings and the upper part the 2, so the 2 lands between them.

Example 3

Input
readings = [0, 0, 1, 1]
Output
[0, 1, 0, 1]

The lower part holds the two zeros and the upper part the two ones, and taking each from the back alternates them.

Constraints

  • 1 <= readings.length <= 5 * 10^4
  • 0 <= readings[i] <= 5000
  • the readings always allow a zigzag

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def wiggle_sort(readings: list[int]) -> list[int]:
Java
public int[] wiggleSort(int[] readings)