I want to implement the heap sort algorithm in JavaScript using MinHeap. But the code output isn't correct.
My dataset had 1000 numbers and I'm trying to heapify all data.
import * as fs from 'fs';
// Read the input file
const input = fs.readFileSync('data.txt', 'utf8');
let data = input.split(" ").map(Number);
// Call the main function to build the min-heap and print the results
main(data);
// Min-heapify function
function heapify(data, i, n) {
let left = 2 * i;
let right = 2 * i + 1;
let smallest = i;
if (right <= n && left <= n && data[right] < data[left]) {
if (data[right] < data[i]) {
smallest = right;
}
}
else (right <= n && left <= n && data[right] > data[left])
{
if (data[left] < data[i]) {
smallest = left;
}
}
//if smallest is changed to original left or right
if (smallest != i) {
// Swap data[i] and data[smallest]
[data[i], data[smallest]] = [data[smallest], data[i]];
//Recursively heapify the subtree
heapify(data, smallest, n);
}
return data;
}
// Build min-heap function
function buildMinHeap(data) {
const n = data.length - 1;
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
heapify(data, i, n);
}
}
// Main function
function main(data) {
// Build a min-heap
buildMinHeap(data);
// Print the first 20 values data[1], data[2], ..., data[20]
console.log("First 20 values:");
const n = data.length;
for (let i = 0; i <= 19 && i <= n; i++) {
process.stdout.write(data[i] + ',');
}
console.log("Last 20 values:");
for (let i = n - 1; i >= n - 20 && i >= 1; i--) {
process.stdout.write(data[i] + ',');
}
}
What's wrong with this code?
There are these issues in
heapify:As arrays have 0 as the first index, the "formula"
left = 2 * iis wrong; it would say that the left child of the root (at 0) is ... 0. You needleft = 2 * i + 1andright = 2 * i + 2.You have an
elsefollowed by comparison expression. That doesn't do what you think it does. You needelse ifThe
if ... elsestructure does not include what to do if the node has only a left child, i.e. whenleft == n. Currently your code then assumes that the smallest is ati, but you never check whether that is true.In
buildMinHeapthere is this problem:nwill be set to 3 and the loop will start at 0. This is wrong. It should start at 1, as 1 is the parent of the node atn.Not a problem, but
if you have
right <= nthen testing forleft <= nis useless: if the first is true, then the second is guaranteed to be true too asleftis one less thanright.heapifyshould not have to return anything. The mutation happens in-place.Comments should not be saying trivial things like
// Build min-heap function. This doesn't help the reader. Instead provide comments to explain the "why?".Here is the correction for these two functions:
Finally, this is not an implementation of heap sort. This only builds the heap. A heap is not a sorted array, but a data structure that ensures the heap property. This can be useful for several algorithms, including heapsort. For implementing heapsort, you need to keep extracting the minimum from the heap until it is empty. You can save the extracted values in the part of the array that is no longer used by the shrinking heap.
Here is a function you could add to your code to accomplish that:
You can call
heapSort(data)from your main function.Be aware though, that when you use a min-heap, then heapsort will sort in descending order. If you want the result to be sorted in ascending order, you should change your heap implementation into a max-heap.