mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2026-03-13 08:51:02 +08:00
Add heap sort.
This commit is contained in:
@@ -1,10 +1,10 @@
|
||||
import Comparator from '../../utils/comparator/Comparator';
|
||||
|
||||
export default class MinHeap {
|
||||
constructor() {
|
||||
constructor(comparatorFunction) {
|
||||
// Array representation of the heap.
|
||||
this.heapContainer = [];
|
||||
this.compare = new Comparator();
|
||||
this.compare = new Comparator(comparatorFunction);
|
||||
}
|
||||
|
||||
static getLeftChildIndex(parentIndex) {
|
||||
@@ -120,6 +120,10 @@ export default class MinHeap {
|
||||
}
|
||||
}
|
||||
|
||||
isEmpty() {
|
||||
return !this.heapContainer.length;
|
||||
}
|
||||
|
||||
toString() {
|
||||
return this.heapContainer.toString();
|
||||
}
|
||||
|
||||
@@ -6,12 +6,14 @@ describe('MinHeap', () => {
|
||||
|
||||
expect(minHeap).toBeDefined();
|
||||
expect(minHeap.peek()).toBeNull();
|
||||
expect(minHeap.isEmpty()).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should add items to the heap and heapify it up', () => {
|
||||
const minHeap = new MinHeap();
|
||||
|
||||
minHeap.add(5);
|
||||
expect(minHeap.isEmpty()).toBeFalsy();
|
||||
expect(minHeap.peek()).toBe(5);
|
||||
expect(minHeap.toString()).toBe('5');
|
||||
|
||||
|
||||
Reference in New Issue
Block a user