Skip to content

Commit 461eb07

Browse files
committed
heap sort
1 parent 7f4b581 commit 461eb07

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

src/jssort.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,44 @@ var jssort = jssort || {};
217217
jss.threeWaysQuickSort(a, lo, lt-1, compare);
218218
jss.threeWaysQuickSort(a, gt+1, hi, compare);
219219
};
220+
221+
jss.heapSort = function(a, compare) {
222+
if (!compare) {
223+
compare = function (a1, a2){
224+
return a1 - a2;
225+
};
226+
}
227+
228+
var N = a.length;
229+
var N2 = Math.floor(N / 2);
230+
for (var k = N2; k <= 1; --k){
231+
jss.sink(a, k, N);
232+
}
233+
234+
while (N > 1) {
235+
jss.exchange(a, jss.heapIndex(1), jss.heapIndex(N));
236+
N--;
237+
jss.sink(a, 1, N);
238+
}
239+
};
240+
241+
jss.sink = function(a, k, N) {
242+
while (k * 2 <= N) {
243+
var child = k * 2;
244+
if(child < N && jss.less(a[jss.heapIndex(child), jss.heapIndex(child+1)])) {
245+
child++;
246+
}
247+
if(jss.less(a[jss.heapIndex(k)], a[jss.heapIndex(child)])) {
248+
jss.exchange(a, jss.heapIndex(k), jss.heapIndex(child));
249+
} else {
250+
break;
251+
}
252+
}
253+
};
220254

255+
jss.heapIndex = function(i) {
256+
return i - 1;
257+
};
221258
})(jssort);
222259

223260
if(module) {

test/three-ways-quick-sort-spec.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ describe("Three Ways Quick Sort", function() {
88

99
var a = [3, 4, 5, 1, 2, 4, 6, 8, 9, 3, 4, 67, 34, 53, 44, 2];
1010
jssort.threeWaysQuickSort(a);
11-
console.log(a);
1211
for(var i = 1; i < a.length; ++i){
1312
expect(a[i-1]).not.to.above(a[i]);
1413
}

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