Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Heapsort

In this article, we will learn about heapsort in javascript.

Heapsort can be thought of as an improved selection sort: like selection sort, heapsort divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element from it and inserting it into the sorted region. Unlike selection sort, heapsort does not waste time with a linear-time scan of the unsorted region; rather, heap sort maintains the unsorted region in a heap data structure to more quickly find the largest element in each step.
Source: wikipedia

Now let’s implement the algorithm in Javascript.

var unsortedArraySize;
const buildMaxHeap = (unsortedArray, i) => {
    let left = 2 * i + 1;
    let right = 2 * i + 2;
    let max = i;

    if (left < unsortedArraySize && unsortedArray[left] > unsortedArray[max]) {
        max = left;
    }

    if (right < unsortedArraySize && unsortedArray[right] > unsortedArray[max])     {
        max = right;
    }

    if (max != i) {
        swap(unsortedArray, i, max);
        buildMaxHeap(unsortedArray, max);
    }
}

const swap = (sortedArray, unsortedIndex, sortedIndex) => {
    let temp = sortedArray[unsortedIndex];
    sortedArray[unsortedIndex] = sortedArray[sortedIndex];
    sortedArray[sortedIndex] = temp;
};

const heapSort = (unsortedArray) => {
    unsortedArraySize = unsortedArray.length;

    for (let i = Math.floor(unsortedArraySize / 2); i >= 0; i -= 1)      {
        buildMaxHeap(unsortedArray, i);
      }

    for (i = unsortedArray.length - 1; i > 0; i--) {
        swap(unsortedArray, 0, i);
        unsortedArraySize--;
        buildMaxHeap(unsortedArray, 0);
    }
}

let sortedArray = [3,2,4,3,5,6,7,5,3];
heapSort(sortedArray);
console.log(sortedArray);
// output
// [2, 3, 3, 3, 4, 5, 5, 6, 7]