Add heap sort.

This commit is contained in:
Oleksii Trekhleb
2018-04-14 10:29:36 +03:00
parent 053b365f24
commit 36bbfed6a1
9 changed files with 143 additions and 38 deletions

View File

@@ -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();
}

View File

@@ -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');