Heap Sort
MediumP3Coding
Sort an array of integers in ascending order using heap sort and return the sorted array.
Heap sort builds a max-heap inside the array, then repeatedly swaps the root (the maximum) with the last element of the heap, shrinks the heap by one and restores the heap property. Write the heap logic yourself rather than using a library heap or built-in sort.
Example 1
- Input
- nums = [4,10,3,5,1]
- Output
- [1,3,4,5,10]
Example 2
- Input
- nums = [2,1]
- Output
- [1,2]
Example 3
- Input
- nums = []
- Output
- []
Constraints
- 0 <= nums.length <= 1000
- -10^4 <= nums[i] <= 10^4
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 10. ⌘Enter runs, ⌘⇧Enter submits.