# JavaScript Searching and Sorting Algorithm: Heap sort

## JavaScript Searching and Sorting Algorithm: Exercise-3 with Solution

Write a JavaScript program to sort a list of elements using Heap sort.

In computer science, heapsort (invented by J. W. J. Williams in 1964) is a comparison-based sorting algorithm. Heapsort can be thought of as an improved selection sort: like that algorithm, it divides its input into a sorted and an unsorted region, and it interactively shrinks the unsorted region by extracting the largest element and moving that to the sorted region. The improvement consists of the use of a heap data structure rather than a linear-time search to find the maximum. Although somewhat slower in practice on most machines than a well-implemented quicksort, it has the advantage of a more favorable worst-case O(n log n) runtime. Heapsort is an in-place algorithm, but it is not a stable sort.

A run of the heapsort algorithm sorting an array of randomly permuted values. In the first stage of the algorithm the array elements are reordered to satisfy the heap property. Before the actual sorting takes place, the heap tree structure is shown briefly for illustration.

Animation credits : RolandH

Sample Solution: -

HTML Code:

``````<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>JavaScript program of Heap sort</title>
<body></body>
</html>
```
```

JavaScript Code:

``````
var array_length;
/* to create MAX  array */
function heap_root(input, i) {
var left = 2 * i + 1;
var right = 2 * i + 2;
var max = i;

if (left < array_length && input[left] > input[max]) {
max = left;
}

if (right < array_length && input[right] > input[max])     {
max = right;
}

if (max != i) {
swap(input, i, max);
heap_root(input, max);
}
}

function swap(input, index_A, index_B) {
var temp = input[index_A];

input[index_A] = input[index_B];
input[index_B] = temp;
}

function heapSort(input) {

array_length = input.length;

for (var i = Math.floor(array_length / 2); i >= 0; i -= 1)      {
heap_root(input, i);
}

for (i = input.length - 1; i > 0; i--) {
swap(input, 0, i);
array_length--;

heap_root(input, 0);
}
}

var arr = [3, 0, 2, 5, -1, 4, 1];
heapSort(arr);
console.log(arr);
```
```

Sample Output:

```[-1,0,1,2,3,4,5]
```

Flowchart:

Live Demo:

See the Pen searching-and-sorting-algorithm-exercise-3 by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

﻿

## JavaScript: Tips of the Day

Returns the distance between two points

Example:

```const tips_distance = (p0, q0, p1, q1) => Math.hypot(p1 - p0, q1 - q0);
console.log(tips_distance(1, 3, 5, 7));
```

Output:

```5.656854249492381
```