Skip to content

Commit

Permalink
unit test for heap sort
Browse files Browse the repository at this point in the history
  • Loading branch information
cschen1205 committed May 25, 2017
1 parent 461eb07 commit 67f9778
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
15 changes: 9 additions & 6 deletions src/jssort.js
Original file line number Diff line number Diff line change
Expand Up @@ -227,25 +227,28 @@ var jssort = jssort || {};

var N = a.length;
var N2 = Math.floor(N / 2);
for (var k = N2; k <= 1; --k){
jss.sink(a, k, N);
for (var k = N2; k >= 1; --k){
jss.sink(a, k, N, compare);
}

while (N > 1) {

jss.exchange(a, jss.heapIndex(1), jss.heapIndex(N));
N--;
jss.sink(a, 1, N);
jss.sink(a, 1, N, compare);

}
};

jss.sink = function(a, k, N) {
jss.sink = function(a, k, N, compare) {
while (k * 2 <= N) {
var child = k * 2;
if(child < N && jss.less(a[jss.heapIndex(child), jss.heapIndex(child+1)])) {
if(child < N && jss.less(a[jss.heapIndex(child)], a[jss.heapIndex(child+1)], compare)) {
child++;
}
if(jss.less(a[jss.heapIndex(k)], a[jss.heapIndex(child)])) {
if(jss.less(a[jss.heapIndex(k)], a[jss.heapIndex(child)], compare)) {
jss.exchange(a, jss.heapIndex(k), jss.heapIndex(child));
k = child;
} else {
break;
}
Expand Down
28 changes: 28 additions & 0 deletions test/heap-sort-spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
var expect = require("chai").expect;
var jssort = require("../src/jssort");

describe("Heap Sort", function() {
describe("Sort Ascendingly", function() {

it("should sort ascedingly when no compare function is provided", function() {

var a = [3, 4, 5, 1, 2, 4, 6, 8, 9, 3, 4, 67, 34, 53, 44, 2];
jssort.heapSort(a);
for(var i = 1; i < a.length; ++i){
expect(a[i-1]).not.to.above(a[i]);
}
});

it("should sort ascedingly using the provided comparer", function() {

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]];
jssort.heapSort(a, function(a1, a2){
return a1[1] - a2[1];
});
for(var i = 1; i < a.length; ++i){
expect(a[i-1][1]).not.to.above(a[i][1]);
}
});
});

});

0 comments on commit 67f9778

Please sign in to comment.