Example 1
- Input
- nums = [5, 2, 3, 1]
- Output
- [1, 2, 3, 5]
The smallest value 1 moves to the front and the largest value 5 moves to the end. The middle values remain in ascending order.
Rearrange integer values into ascending order without calling a library sort. Compare Quick Sort, Merge Sort and Heap Sort by their time guarantees and memory use.
Return nums in ascending order, preserving every value and its number of occurrences. Implement the sorting yourself rather than calling a built-in sorting function.
The target is time with as little extra storage as possible. Randomized Quick Sort illustrates expected performance; Merge Sort and Heap Sort guarantee the time bound. Heap Sort is selected here because it also uses constant auxiliary space.
1 <= nums.length <= 50000-50000 <= nums[i] <= 50000The smallest value 1 moves to the front and the largest value 5 moves to the end. The middle values remain in ascending order.
Both copies of 0 and both copies of 1 are retained. Sorting changes positions, not frequencies.
One element is already ordered. No partition, merge or heap extraction is needed.
Negative values precede zero and positive values; the two equal 2 values occupy the last two positions.
A quadratic scan repeatedly searches the entire unsorted part for its next value. Faster comparison sorts organize those comparisons: Quick Sort groups values around a pivot, Merge Sort combines runs already in order, and Heap Sort keeps the largest remaining value at a tree root. For [5, 2, 3, 1], all three produce [1, 2, 3, 5], but they preserve different invariants and use different storage. Stable sorting preserves the original relative order of equal-valued records; that matters for records with attached data, although equal integers are indistinguishable here.
Reveal Three-Way Quick Sort: intuition, complexity, and code
Choose a sorting invariant to match the actual requirements: randomized partitions for expected speed, stable merging when equal-record order matters, or heap extraction for guaranteed O(n log n) time with constant auxiliary space.