Created
October 20, 2017 11:42
-
-
Save loke-dev/7dd4d6b4b9fa527a3343d83b4d9c534c to your computer and use it in GitHub Desktop.
Heap sort benchmark test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var a = randomArray(100000, 100000); | |
function randomArray(length, max) { | |
return Array.apply(null, Array(length)).map(function() { | |
return Math.round(Math.random() * max); | |
}); | |
} | |
function swap(a, i, j) { | |
var tmp = a[i]; | |
a[i] = a[j]; | |
a[j] = tmp; | |
} | |
function max_heapify(a, i, length) { | |
while (true) { | |
var left = i*2 + 1; | |
var right = i*2 + 2; | |
var largest = i; | |
if (left < length && a[left] > a[largest]) { | |
largest = left; | |
} | |
if (right < length && a[right] > a[largest]) { | |
largest = right; | |
} | |
if (i == largest) { | |
break; | |
} | |
swap(a, i, largest); | |
i = largest; | |
} | |
} | |
function heapify(a, length) { | |
for (var i = Math.floor(length/2 - 1); i >= 0; i--) { | |
max_heapify(a, i, length); | |
} | |
} | |
function heapsort(a) { | |
heapify(a, a.length); | |
for (var i = a.length - 1; i > 0; i--) { | |
swap(a, i, 0); | |
max_heapify(a, 0, i); | |
} | |
} | |
var start = new Date().getTime(); | |
heapsort(a); | |
var end = new Date().getTime(); | |
var time = end - start; | |
console.log("Done") | |
console.log("Sorted an array with " + a.length + " elements") | |
console.log("It took " + time + " ms to sort!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment