Heap Sort

Heaps Theory and Implementation Medium

Given an array of integers nums, sort the array in non-decreasing order using the heap sort algorithm. Sort the given array itself, there is no need to return anything.


A sorted array in non-decreasing order is one in which each element is either greater than or equal to all the elements to its left in the array.

Examples:

Input: nums = [7, 4, 1, 5, 3]

Output: [1, 3, 4, 5, 7]

Explanation:1 <= 3 <= 4 <= 5 <= 7.

One possible way to get the sorted array using heapSort :

[7, 4, 1, 5, 3] -> [3, 4, 1, 5, 7]

-> [5, 4, 1, 3, 7] -> [3, 4, 1, 5, 7]

-> [4, 3, 1, 5, 7] -> [1, 3, 4, 5, 7]

-> [3, 1, 4, 5, 7] -> [1, 3, 4, 5, 7]

-> [1, 3, 4, 5, 7] -> [1, 3, 4, 5, 7]

Input: nums = [5, 4, 4, 1, 1]

Output: [1, 1, 4, 4, 5]

Explanation: 1 <= 1 <= 4 <= 4 <= 5.

Thus the array is sorted in non-decreasing order.

Input: nums = [6, 2, 3, 1, 5]

Constraints

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104
  • nums[i] may contain duplicate values.


Hints

  • "Convert nums into a max-heap (largest element at root). Start heapifying from last non-leaf node (n//2) - 1 down to 0. Use heapify-down to maintain the heap property."
  • "Swap the root (max element) with the last element. Reduce heap size and heapify-down the new root to restore heap order. Repeat until the array is sorted in non-decreasing order."

Company Tags

AMD Electronic Arts Databricks Twilio Intel DoorDash Roblox Activision Blizzard Alibaba PayPal Etsy Oracle Seagate Technology Ubisoft Wayfair Docker PwC McKinsey & Company Rockstar Games MongoDB Stripe OYO Rooms Swiggy Reddit Uber Google Microsoft Amazon Meta Apple Netflix Adobe