This repository was archived by the owner on Feb 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheapSort.ts
More file actions
93 lines (69 loc) · 1.88 KB
/
heapSort.ts
File metadata and controls
93 lines (69 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
class MaxHeap {
private _heap: number[] = [];
constructor() {
this.heap = [];
}
public get heap(): number[] {
return this._heap;
}
public set heap(value: number[]) {
this._heap = value;
}
parentIndex(index: number) {
return Math.floor((index - 1) / 2);
}
leftChildIndex(index: number) {
return 2 * index + 1;
}
rightChildIndex(index: number) {
return 2 * index + 2;
}
swap(a: number, b: number) {
const aux = this.heap[a];
this.heap[a] = this.heap[b];
this.heap[b] = aux;
}
insert(item: number) {
this.heap.push(item);
let index = this.heap.length - 1;
let parent = this.parentIndex(index);
while (this.heap[parent] && this.heap[parent] < this.heap[index]) {
this.swap(parent, index);
index = this.parentIndex(index);
parent = this.parentIndex(index);
}
}
delete() {
const item = this.heap.shift();
this.heap.unshift(this.heap.pop() as number);
let index = 0;
let leftChild = this.leftChildIndex(index);
let rightChild = this.rightChildIndex(index);
while (
(this.heap[leftChild] && this.heap[leftChild] > this.heap[index]) ||
this.heap[rightChild] > this.heap[index]
) {
let max = leftChild;
if (this.heap[rightChild] && this.heap[rightChild] > this.heap[max]) {
max = rightChild;
}
this.swap(max, index);
index = max;
leftChild = this.leftChildIndex(max);
rightChild = this.rightChildIndex(max);
}
return item;
}
}
const heapSort = (unorderedArray: number[]): number[] => {
const sortedArray: number[] = [];
const heap = new MaxHeap();
for (let i = 0; i < unorderedArray.length; ++i) {
heap.insert(unorderedArray[i]);
}
for (let i = 0; i < unorderedArray.length; ++i) {
sortedArray.push(heap.delete() as number);
}
return sortedArray;
};
export default heapSort;