--description--
Now that we can add and remove elements let's see some of the applications heaps can be used for. Heaps are commonly used to implement priority queues because they always store an item of greatest or least value in first position. In addition, they are used to implement a sorting algorithm called heap sort. We'll see how to do this here. Heap sort uses a min heap, the reverse of a max heap. A min heap always stores the element of least value in the root position.
Heap sort works by taking an unsorted array, adding each item in the array into a min heap, and then extracting every item out of the min heap into a new array. The min heap structure ensures that the new array will contain the original items in least to greatest order. This is one of the most efficient sorting algorithms with average and worst case performance of O(nlog(n)).
--instructions--
Let's implement heap sort with a min heap. Feel free to adapt your max heap code here. Create an object MinHeap
with insert
, remove
, and sort
methods. The sort
method should return an array of all the elements in the min heap sorted from smallest to largest.
--hints--
The MinHeap
data structure should exist.
assert(
(function () {
var test = false;
if (typeof MinHeap !== 'undefined') {
test = new MinHeap();
}
return typeof test == 'object';
})()
);
MinHeap
should have a method called insert
.
assert(
(function () {
var test = false;
if (typeof MinHeap !== 'undefined') {
test = new MinHeap();
} else {
return false;
}
return typeof test.insert == 'function';
})()
);
MinHeap
should have a method called remove
.
assert(
(function () {
var test = false;
if (typeof MinHeap !== 'undefined') {
test = new MinHeap();
} else {
return false;
}
return typeof test.remove == 'function';
})()
);
MinHeap
should have a method called sort
.
assert(
(function () {
var test = false;
if (typeof MinHeap !== 'undefined') {
test = new MinHeap();
} else {
return false;
}
return typeof test.sort == 'function';
})()
);
The sort
method should return an array containing all items added to the min heap in sorted order.
assert(
(() => {
if (typeof MinHeap === 'undefined') {
return false;
}
const heap = new MinHeap();
const arr = createRandomArray(25);
for (let i of arr) {
heap.insert(i);
}
const result = heap.sort();
arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++) {
if (arr[i] !== result[i]) {
return false;
}
}
return true;
})()
);
--seed--
--seed-contents--
function isSorted(a){
for(let i = 0; i < a.length - 1; i++)
if(a[i] > a[i + 1])
return false;
return true;
}
// Generate a randomly filled array
function createRandomArray(size = 5){
let a = new Array(size);
for(let i = 0; i < size; i++)
a[i] = Math.floor(Math.random() * 100);
return a;
}
const array = createRandomArray(25);
var MinHeap = function() {
// Only change code below this line
// Only change code above this line
};
--solutions--
// solution required