AlgoFrames

Implement heap sort

Standard · Write code · about 15 min

Sort values in ascending order with heap sort and return the array. Build a max-heap in place, then repeatedly swap the root with the last cell of the heap and sift the new root down.

Do not call a library sort.

Example 1

Input:

[[5,2,9,4,7,1]]

Output:

[1,2,4,5,7,9]

Build-heap gives 9 7 5 4 2 1, then five rounds sort it.

Example 2

Input:

[[3,3,1]]

Output:

[1,3,3]

Equal values are fine; their order does not matter here.

Constraints

  • 0 ≤ values.length ≤ 10,000
  • Values are integers from -100,000 to 100,000

Learn the idea first: Heap sort, a visual lesson.

More Heap sort problems