Skip to content

Commit 22a6af6

Browse files
committed
added heap sort
1 parent 5af6d72 commit 22a6af6

File tree

1 file changed

+48
-2
lines changed

1 file changed

+48
-2
lines changed

chapter10/01-SortingSearchingAlgorithms.js

+48-2
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,47 @@ function ArrayList(){
200200
return array;
201201
};
202202

203+
this.heapSort = function(){
204+
var heapSize = array.length;
205+
206+
buildHeap(array);
207+
208+
while (heapSize > 1) {
209+
heapSize--;
210+
swap(array, 0, heapSize);
211+
heapify(array, heapSize, 0);
212+
}
213+
};
214+
215+
var buildHeap = function(array){
216+
var heapSize = array.length;
217+
for (var i = Math.floor(array.length / 2); i >= 0; i--) {
218+
heapify(array, heapSize, i);
219+
}
220+
};
221+
222+
var heapify = function(array, heapSize, i){
223+
var left = i * 2 + 1,
224+
right = i * 2 + 2,
225+
largest = i;
226+
227+
if (left < heapSize && array[left] > array[largest]) {
228+
largest = left;
229+
}
230+
231+
if (right < heapSize && array[right] > array[largest]) {
232+
largest = right;
233+
}
234+
235+
console.log('Heap Index = '+ i + ' and Heap Size = ' + heapSize);
236+
237+
if (largest !== i) {
238+
console.log('swap index ' + i + ' with ' + largest + ' (' + + array[i] + ',' + array[largest] + ')');
239+
swap(array, i, largest);
240+
heapify(array, heapSize, largest);
241+
}
242+
};
243+
203244
this.countingSort = function(){
204245

205246
var i,
@@ -229,24 +270,29 @@ function ArrayList(){
229270
var i,
230271
minValue = this.findMinValue(),
231272
maxValue = this.findMaxValue(),
232-
BUCKET_SIZE = 10;
273+
BUCKET_SIZE = 5;
274+
275+
console.log('minValue ' + minValue);
276+
console.log('maxValue ' + maxValue);
233277

234278
bucketSize = bucketSize || BUCKET_SIZE;
235279
var bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1;
236280
var buckets = new Array(bucketCount);
281+
console.log('bucketSize = ' + bucketCount);
237282
for (i = 0; i < buckets.length; i++) {
238283
buckets[i] = [];
239284
}
240285

241286
for (i = 0; i < array.length; i++) {
242287
buckets[Math.floor((array[i] - minValue) / bucketSize)].push(array[i]);
288+
console.log('pushing item ' + array[i] + ' to bucket index ' + Math.floor((array[i] - minValue) / bucketSize));
243289
}
244290

245291
array = [];
246292
for (i = 0; i < buckets.length; i++) {
247293
insertionSort_(buckets[i]);
248294

249-
console.log('bucket ' + i + ': ' + buckets[i].join());
295+
console.log('bucket sorted ' + i + ': ' + buckets[i].join());
250296

251297
for (var j = 0; j < buckets[i].length; j++) {
252298
array.push(buckets[i][j]);

0 commit comments

Comments
 (0)