Skip to content

Commit b15cb5d

Browse files
feat: Heap Sort (TheAlgorithms#182)
1 parent b109436 commit b15cb5d

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

sorts/heap_sort.ts

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* @function heapsort
3+
* @description is a comparison-based sorting algorithm that uses a binary heap data structure to repeatedly select and remove the maximum (for max-heap) or minimum (for min-heap) element and place it at the end of the sorted array.
4+
* @see [Heap Sort](https://www.geeksforgeeks.org/heap-sort/)
5+
* @example MergeSort([7, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 7]
6+
* @Complexity_Analysis
7+
* Space complexity - O(n)
8+
* Time complexity
9+
* Best case - O(nlogn)
10+
* Worst case - O(nlogn)
11+
* Average case - O(nlogn)
12+
*/
13+
14+
// Function to perform the Heap Sort
15+
export const HeapSort = (arr: number[]): number[] => {
16+
17+
buildMaxHeap(arr);
18+
19+
for (let i = arr.length - 1; i > 0; i--) {
20+
swap(arr, 0, i);
21+
heapify(arr, 0, i);
22+
}
23+
24+
return arr;
25+
};
26+
27+
// Function to build a max-heap from an array
28+
function buildMaxHeap(arr: number[]): void {
29+
const n = arr.length;
30+
31+
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
32+
heapify(arr, i, n);
33+
}
34+
}
35+
36+
// Function to heapify a subtree rooted at a given index
37+
function heapify(arr: number[], index: number, size: number): void {
38+
let largest = index;
39+
const left = 2 * index + 1;
40+
const right = 2 * index + 2;
41+
42+
if (left < size && arr[left] > arr[largest]) {
43+
largest = left;
44+
}
45+
46+
if (right < size && arr[right] > arr[largest]) {
47+
largest = right;
48+
}
49+
50+
if (largest !== index) {
51+
swap(arr, index, largest);
52+
heapify(arr, largest, size);
53+
}
54+
}
55+
56+
// Function to swap two elements in an array
57+
function swap(arr: number[], i: number, j: number): void {
58+
const temp = arr[i];
59+
arr[i] = arr[j];
60+
arr[j] = temp;
61+
}

sorts/test/heap_sort.test.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { HeapSort } from "../heap_sort";
2+
3+
describe("Heap Sort", () => {
4+
it("should return the correct value for average case", () => {
5+
expect(HeapSort([1, 4, 2, 5, 9, 6, 3, 8, 10, 7])).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
6+
});
7+
8+
it("should return the correct value for worst case", () => {
9+
expect(HeapSort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
10+
});
11+
12+
it("should return the correct value for best case", () => {
13+
expect(HeapSort([1, 4, 2, 9, 5, 7, 3, 8, 10, 6])).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
14+
});
15+
});

0 commit comments

Comments
 (0)