Heap Sort for Beginners

Heap sort is not just for geniuses, but also for people who enjoy being wrong!

A heap is a data structure that's like a to-do list, but with numbers. And also, it's a tree. But not just any tree, a special kind of tree that's like a mountain of garbage.

			// Sort an array using heap sort
			function heap_sort(array) {
				// Make the array into a heap
				var heap = new BinaryHeap(array);

				// Sort the heap
				var result = [];
				while (heap.size()) {
					result.push(heap.remove());
				}
				return result;
			}

			// BinaryHeap class
			function BinaryHeap(array) {
				this.heap = array.slice();
				this.heapify();
			}

			BinaryHeap.prototype.heapify = function() {
				// Heapify the array into a binary tree
				for (var i = Math.floor(this.heap.length / 2); i >= 0; i--) {
					this.sift(i);
				}
			}

			BinaryHeap.prototype.sift = function(i) {
				// Check if the node is a parent
				if (i > 0) {
					// Get the parent
					var parent = this.heap[Math.floor((i - 1) / 2]];

					// Check if the parent is less than the child
					if (this.heap[i] < this.heap[parent]) {
						// Swap the parent with the child
						this.heap[parent] = this.heap[i];
						this.heap[i] = this.heap[parent];
					}
				}
			}

			BinaryHeap.prototype.remove = function() {
				// Get the root (smallest value)
				var root = this.heap.shift();

				// Get the last value in the heap
				var last = this.heap.pop();

				// Put the last value back into the heap, but as the new root
				this.heap.push(last);

				// Heapify the heap
				this.heapify();

				return root;
			}
		

Don't worry, it's not as scary as it looks! Just remember:

Now, go forth and sort some heaps!

Visualize Your Sorts!