Heaps Building a heap
405. Heap Sort
You are given an array of integers nums. Sort it in ascending order, smallest first, using heap sort.
Heap sort arranges the values as a max heap: a binary tree, stored in the array itself, in which every parent is at least as large as its children. The largest value is then at the root. Heap sort takes the largest value out again and again, and each one goes to its final place at the back of the array.
Change nums itself. The function returns nothing; the answer is what nums holds after it finishes. Every
copy of a repeated value stays, so equal values end up next to each other. Try to use only a few variables of
extra memory, with no second array.
The judge checks only the sorted array, so a call to your language's built-in sort or priority queue would also be accepted. That skips the whole exercise, though. Write heap sort yourself.
Example 1
Input: nums = [7, 2, 9, 4, 7, -1]
[-1,2,4,7,7,9]Explanation: The smallest value, −1, comes first and the 9 comes last. Both 7s stay, side by side.
Example 2
Input: nums = [-5, 1000000000, -1000000000, 0, -5]
[-1000000000,-5,-5,0,1000000000]Explanation: Both ends of the range can appear. The negative values come first, and the two −5s end up next to each other.
Example 3
Input: nums = [-2, 0, 0, 3, 11]
[-2,0,0,3,11]Explanation: The array is already sorted, so it comes back unchanged.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.