Skip to content

Commit 67f9778

Browse files
committed
unit test for heap sort
1 parent 461eb07 commit 67f9778

File tree

2 files changed

+37
-6
lines changed

2 files changed

+37
-6
lines changed

src/jssort.js

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -227,25 +227,28 @@ var jssort = jssort || {};
227227

228228
var N = a.length;
229229
var N2 = Math.floor(N / 2);
230-
for (var k = N2; k <= 1; --k){
231-
jss.sink(a, k, N);
230+
for (var k = N2; k >= 1; --k){
231+
jss.sink(a, k, N, compare);
232232
}
233233

234234
while (N > 1) {
235+
235236
jss.exchange(a, jss.heapIndex(1), jss.heapIndex(N));
236237
N--;
237-
jss.sink(a, 1, N);
238+
jss.sink(a, 1, N, compare);
239+
238240
}
239241
};
240242

241-
jss.sink = function(a, k, N) {
243+
jss.sink = function(a, k, N, compare) {
242244
while (k * 2 <= N) {
243245
var child = k * 2;
244-
if(child < N && jss.less(a[jss.heapIndex(child), jss.heapIndex(child+1)])) {
246+
if(child < N && jss.less(a[jss.heapIndex(child)], a[jss.heapIndex(child+1)], compare)) {
245247
child++;
246248
}
247-
if(jss.less(a[jss.heapIndex(k)], a[jss.heapIndex(child)])) {
249+
if(jss.less(a[jss.heapIndex(k)], a[jss.heapIndex(child)], compare)) {
248250
jss.exchange(a, jss.heapIndex(k), jss.heapIndex(child));
251+
k = child;
249252
} else {
250253
break;
251254
}

test/heap-sort-spec.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
var expect = require("chai").expect;
2+
var jssort = require("../src/jssort");
3+
4+
describe("Heap Sort", function() {
5+
describe("Sort Ascendingly", function() {
6+
7+
it("should sort ascedingly when no compare function is provided", function() {
8+
9+
var a = [3, 4, 5, 1, 2, 4, 6, 8, 9, 3, 4, 67, 34, 53, 44, 2];
10+
jssort.heapSort(a);
11+
for(var i = 1; i < a.length; ++i){
12+
expect(a[i-1]).not.to.above(a[i]);
13+
}
14+
});
15+
16+
it("should sort ascedingly using the provided comparer", function() {
17+
18+
var a = [[3, 2.3], [4, 3.1], [5, 1.1], [1, 4.2], [2, 4.2], [4, 5.3], [6, 7.4], [8, 5.1], [9, 1.9], [3, 1.2], [4, 3.4], [67, 6.7], [34, 3], [53, 5], [44, 4.2], [2, 0]];
19+
jssort.heapSort(a, function(a1, a2){
20+
return a1[1] - a2[1];
21+
});
22+
for(var i = 1; i < a.length; ++i){
23+
expect(a[i-1][1]).not.to.above(a[i][1]);
24+
}
25+
});
26+
});
27+
28+
});

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy