Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 202ca9f

Browse files
feat(heap): add min/max/median-heaps
1 parent 7279e5c commit 202ca9f

File tree

9 files changed

+372
-153
lines changed

9 files changed

+372
-153
lines changed

‎src/data-structures/trees/heap.js renamed to ‎src/data-structures/heaps/heap.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,58 @@
1+
/**
2+
* Heap data structure a.k.a Priority Queue
3+
*
4+
* Used to get min or max values from a collection in constant time.
5+
*
6+
* @author Adrian Mejia <adrian@adrianmejia.com>
7+
*/
18
class Heap {
29
constructor(comparator = (a, b) => a - b) {
310
this.array = [];
411
this.comparator = (i1, i2) => comparator(this.array[i1], this.array[i2]);
512
}
613

14+
/**
15+
* Insert element
16+
* @runtime O(log n)
17+
* @param {any} value
18+
*/
719
add(value) {
820
this.array.push(value);
921
this.bubbleUp();
1022
}
1123

24+
/**
25+
* Retrieves, but does not remove, the head of this heap
26+
* @runtime O(1)
27+
*/
1228
peek() {
1329
return this.array[0];
1430
}
1531

32+
/**
33+
* Retrieves and removes the head of this heap, or returns null if this heap is empty.
34+
* @runtime O(log n)
35+
*/
1636
remove() {
37+
if (!this.size()) return null;
1738
this.swap(0, this.size() - 1);
1839
const value = this.array.pop();
1940
this.bubbleDown();
2041
return value;
2142
}
2243

44+
/**
45+
* Returns the number of elements in this collection.
46+
* @runtime O(1)
47+
*/
2348
size() {
2449
return this.array.length;
2550
}
2651

52+
/**
53+
* Move new element upwards on the heap, if it's out of order
54+
* @runtime O(log n)
55+
*/
2756
bubbleUp() {
2857
let index = this.size() - 1;
2958
const parent = (i) => Math.ceil(i / 2 - 1);
@@ -33,6 +62,10 @@ class Heap {
3362
}
3463
}
3564

65+
/**
66+
* After removal, moves element downwards on the heap, if it's out of order
67+
* @runtime O(log n)
68+
*/
3669
bubbleDown() {
3770
let index = 0;
3871
const left = (i) => 2 * i + 1;
@@ -47,9 +80,20 @@ class Heap {
4780
}
4881
}
4982

83+
/**
84+
* "Private": Swap elements on the heap
85+
* @runtime O(1)
86+
* @param {number} i1 index 1
87+
* @param {number} i2 index 2
88+
*/
5089
swap(i1, i2) {
5190
[this.array[i1], this.array[i2]] = [this.array[i2], this.array[i1]];
5291
}
5392
}
5493

94+
// aliases
95+
Heap.prototype.poll = Heap.prototype.remove;
96+
Heap.prototype.offer = Heap.prototype.add;
97+
Heap.prototype.element = Heap.prototype.peek;
98+
5599
module.exports = Heap;

‎src/data-structures/heaps/heap.spec.js

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
const Heap = require('./heap');
2+
const PriorityQueue = require('./priority-queue');
3+
const MaxHeap = require('./max-heap');
4+
const MinHeap = require('./min-heap');
5+
6+
[[Heap], [PriorityQueue], [MinHeap]].forEach(([DS, arg]) => {
7+
describe('Min-Heap (Priority Queue)', () => {
8+
let heap;
9+
10+
beforeEach(() => {
11+
heap = new DS(arg);
12+
});
13+
14+
describe('#contructor', () => {
15+
it('should initialize', () => {
16+
expect(heap).not.toBe(undefined);
17+
});
18+
});
19+
20+
describe('#add', () => {
21+
it('should add an element', () => {
22+
expect(heap.add(1)).toBe(undefined);
23+
expect(heap.array).toEqual([1]);
24+
expect(heap.size()).toBe(1);
25+
});
26+
27+
it('should keep things in order', () => {
28+
heap.add(3);
29+
expect(heap.array[0]).toEqual(3);
30+
heap.add(2);
31+
expect(heap.array[0]).toEqual(2);
32+
heap.add(1);
33+
expect(heap.array[0]).toEqual(1);
34+
expect(heap.size()).toEqual(3);
35+
});
36+
});
37+
38+
describe('#remove', () => {
39+
it('should work', () => {
40+
heap.add(1);
41+
heap.add(0);
42+
expect(heap.remove()).toBe(0);
43+
expect(heap.size()).toBe(1);
44+
expect(heap.array).toEqual([1]);
45+
});
46+
47+
it('should return null if empty', () => {
48+
heap = new Heap();
49+
expect(heap.remove()).toBe(null);
50+
});
51+
});
52+
53+
describe('when has elements', () => {
54+
beforeEach(() => {
55+
heap.add(1);
56+
heap.add(2);
57+
heap.add(3);
58+
heap.add(0);
59+
});
60+
61+
describe('#peek', () => {
62+
it('should get min', () => {
63+
expect(heap.peek()).toEqual(0);
64+
});
65+
});
66+
67+
describe('#remove', () => {
68+
it('should get min', () => {
69+
expect(heap.remove()).toEqual(0);
70+
expect(heap.remove()).toEqual(1);
71+
expect(heap.remove()).toEqual(2);
72+
expect(heap.remove()).toEqual(3);
73+
expect(heap.size()).toBe(0);
74+
});
75+
});
76+
});
77+
});
78+
});
79+
80+
[[Heap, (a, b) => b - a], [PriorityQueue, (a, b) => b - a], [MaxHeap]].forEach(([DS, arg]) => {
81+
describe('Max-Heap (Priority Queue)', () => {
82+
let heap;
83+
84+
beforeEach(() => {
85+
heap = new DS(arg);
86+
});
87+
88+
describe('#contructor', () => {
89+
it('should initialize', () => {
90+
expect(heap).not.toBe(undefined);
91+
});
92+
});
93+
94+
describe('#add', () => {
95+
it('should add an element', () => {
96+
expect(heap.add(1)).toBe(undefined);
97+
expect(heap.array).toEqual([1]);
98+
expect(heap.size()).toBe(1);
99+
});
100+
101+
it('should keep things in order', () => {
102+
heap.add(1);
103+
expect(heap.array[0]).toEqual(1);
104+
heap.add(2);
105+
expect(heap.array[0]).toEqual(2);
106+
heap.add(3);
107+
expect(heap.array[0]).toEqual(3);
108+
expect(heap.size()).toEqual(3);
109+
});
110+
});
111+
112+
describe('#remove', () => {
113+
it('should work', () => {
114+
heap.add(1);
115+
heap.add(0);
116+
expect(heap.remove()).toBe(1);
117+
expect(heap.size()).toBe(1);
118+
expect(heap.array).toEqual([0]);
119+
});
120+
121+
it('should work with duplicates', () => {
122+
heap.add(3);
123+
heap.add(2);
124+
heap.add(3);
125+
heap.add(1);
126+
heap.add(2);
127+
heap.add(4);
128+
heap.add(5);
129+
heap.add(5);
130+
heap.add(6);
131+
132+
expect(heap.remove()).toEqual(6);
133+
expect(heap.remove()).toEqual(5);
134+
expect(heap.remove()).toEqual(5);
135+
expect(heap.remove()).toEqual(4);
136+
});
137+
});
138+
139+
describe('when has elements', () => {
140+
beforeEach(() => {
141+
heap.add(1);
142+
heap.add(2);
143+
heap.add(3);
144+
heap.add(0);
145+
});
146+
147+
describe('#peek', () => {
148+
it('should get min', () => {
149+
expect(heap.peek()).toEqual(3);
150+
});
151+
});
152+
153+
describe('#remove', () => {
154+
it('should get min when duplicates', () => {
155+
expect(heap.remove()).toEqual(3);
156+
expect(heap.remove()).toEqual(2);
157+
expect(heap.remove()).toEqual(1);
158+
expect(heap.remove()).toEqual(0);
159+
expect(heap.size()).toBe(0);
160+
});
161+
});
162+
});
163+
});
164+
});

‎src/data-structures/heaps/max-heap.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
const Heap = require('./heap');
2+
3+
class MaxHeap extends Heap {
4+
constructor() {
5+
super((a, b) => b - a);
6+
}
7+
}
8+
module.exports = MaxHeap;
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
const Heap = require('./heap');
2+
3+
/**
4+
* Median Heap using one MaxHeap and one MinHeap.
5+
*
6+
* Each heap contains about one half of the data.
7+
* Every element in the min-heap is greater or equal to the median,
8+
* and every element in the max-heap is less or equal to the median.
9+
*
10+
* @author Adrian Mejia <adrian@adrianmejia.com>
11+
*/
12+
class MedianHeap {
13+
constructor() {
14+
this.min = new Heap((a, b) => a - b);
15+
this.max = new Heap((a, b) => b - a);
16+
}
17+
18+
/**
19+
* Add a value to the heap
20+
* @runtime O(log n)
21+
* @param {any} value
22+
*/
23+
add(value) {
24+
if (value > this.findMedian()) {
25+
// If the new element is greater than the current median, it goes to the min-heap.
26+
this.min.add(value);
27+
} else {
28+
// If it is less than the current median, it goes to the max heap.
29+
this.max.add(value);
30+
}
31+
32+
// rebalance if the sizes of the heaps differ by more than one element
33+
if (Math.abs(this.min.size() - this.max.size()) > 1) {
34+
// extract the min/max from the heap with more elements and insert it into the other heap.
35+
if (this.min.size() > this.max.size()) {
36+
this.max.add(this.min.remove());
37+
} else {
38+
this.min.add(this.max.remove());
39+
}
40+
}
41+
}
42+
43+
/**
44+
* Find median
45+
* @runtime O(1)
46+
*/
47+
findMedian() {
48+
let median;
49+
50+
if (this.max.size() === this.min.size()) {
51+
// When both heaps contain the same number of elements,
52+
// the total number of elements is even.
53+
// The median is the mean of the two middle elements.
54+
median = (this.max.peek() + this.min.peek()) / 2;
55+
} else if (this.max.size() > this.min.size()) {
56+
// when the max-heap contains one more element than the min-heap,
57+
// the median is in the top of the max-heap.
58+
median = this.max.peek();
59+
} else {
60+
// When the min-heap contains one more element than the max-heap,
61+
// the median is in the top of the min-heap.
62+
median = this.min.peek();
63+
}
64+
return median;
65+
}
66+
67+
/**
68+
* Return size of the heap.
69+
*/
70+
size() {
71+
return this.min.size() + this.max.size();
72+
}
73+
}
74+
75+
module.exports = MedianHeap;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /