~/coding-interview/heap-sort-algorithm.md

Heap Sort Algorithm

2 min readJuly 03, 2019by Gorav Singal#coding-interview#sorting-algorithms#heap-sort
// TL;DR

Build a max-heap, swap root (max) with last element, shrink heap, heapify. Repeat until sorted. O(n log n) time, in-place.

Heap Sort Algorithm

This is another very useful sorting algorithm based on Heap data structure. Read more about Heap Data Structure

In this algorithn, we first prepare heap which satisfies max-heap property. Once we get out max heap ready. We get maximum element at the top. We swap this element with the last index element. And, reduce heapsize by one. Now, since we have put a newer element on top. We will just run max_heapify() algorithm on this array with new heapsize.

Finally we get the sorted array.

Heap Sort Algorithm

  • Build a max heap (using max_heapify())
  • In a loop starting from last index
    • swap 0-index value with current index value (which is the last index in our heap)
    • reduce heap size by one. Means, largest element is done. Lets work on remaining array.
    • Run max_heapify() on 0-index

See the code here:

public class HeapSort {
	private int[] arr;
	private int heapsize;

	public HeapSort(int[] arr) {
		this.arr = arr;
		this.heapsize = this.arr.length;
	}
	
	private int getLeftChild(int index) {
		return (index * 2) + 1;
	}
	private int getRightChild(int index) {
		return (index * 2) + 2;
	}
	
	private void max_heapify(int index) {
		int l = this.getLeftChild(index);
		int r = this.getRightChild(index);
		
		int indexOfLargest = index;
		if (l < this.heapsize && this.arr[l] > this.arr[index]) {
			indexOfLargest = l;
		}

		if (r < this.heapsize && this.arr[r] > this.arr[indexOfLargest]) {
			indexOfLargest = r;
		}
		
		if (indexOfLargest != index) {
			ArrayUtils.swap(this.arr, index, indexOfLargest);
			this.max_heapify(indexOfLargest);
		}
	}
	
	private void buildMaxHeap() {
		for (int i=this.heapsize/2; i>=0; i--) {
			this.max_heapify(i);
		}
	}
	
	public void doHeapSort() {
		this.buildMaxHeap();
		int l = this.arr.length;
		for (int i=l-1; i>0; i--){
			ArrayUtils.swap(this.arr, 0, i);
			this.heapsize--;
			
			this.max_heapify(0);
		}
	}
}

Graphical Example

Heap Sort Example

Key Points

  • This is an in-place algorithm.
  • Uses Heap data structure
  • Performance is very good. its complexity is O(n log n)

Runtime complexity

The algorithm runs on O(n log n) in worst/average case.

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Radix Sort Algorithm

Radix Sort Algorithm

A number consists of digits. Example: 843. Its a 3-digit number. Radix sort…

Counting Sort Algorithm

Counting Sort Algorithm

Counting sort runs on relatively smaller set of input. Counting sort calculates…

Quick Sort Algorithm

Quick Sort Algorithm

This algorithm is very useful for large input. And, is quite efficient one. It…

Merge Sort Algorithm

Merge Sort Algorithm

This algorithm is very efficient one, and is classic example of Divide and…

Bubble Sort Algorithm

Bubble Sort Algorithm

This is kind of preliminary technique of sorting. And, this is the first…

Selection Sort Algorithm

Selection Sort Algorithm

It is one of a simple algorithm to study for a beginner to understanding sorting…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…