Binary Heap Sort Algorithm in JavaScript

Use Case:

This post is a follow up of my previous post on building a binary heap in JavaScript. Heap sort is an efficient sorting algorithm - O(n log n) - (both for timing and storage) that compares values against each other. Below is my concise implementation of this algorithm.

JavaScript

function heapSort(heap) {
	for (i = heap.array().length - 1; i >= 0; i--) {
		console.log(heap.extractMax())
	}
}

Once we constructed our binary heap (as outlined in the previous post), we simply need to create a loop that will run for the size of the heap and return our maximum values.

In this example, we're just logging them to the console but you could add them to a new data type starting at the end and working your way forward (or reverse - depending on ascending or descending order).

JavaScript

// Array to Heap, then call Heap Sort
var array = [5,2,3,8,1,6,7,3,4,9]
function arrayToHeap(array) {

	// Create a new heap and insert each value from array
	var heap = new Heap(10)
	for (i = 0; i < array.length; i++) {
		heap.insert(array[i])
	}

	// After building heap, call heapSort algorithm
	heapSort(heap)
}
arrayToHeap(array)

To call our 'heapSort' function, we'll first iterate through the array variable to pull in our values, add them to our heap using our 'heap.insert' function, and then call our 'heapSort' function to log the values in descending order to the console.

Tweet me @tylerewillis

Or send me an email: