Created
August 19, 2016 18:52
-
-
Save falkirks/0897438318a53c1d475860de32f3532f to your computer and use it in GitHub Desktop.
Bored on a bus...
This file contains hidden or 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
// Being bored on a bus | |
// Simple quickSort, always take index zero as the pivot | |
var unsorted = [3, 5, 1, 7, 6, 7, 3]; | |
function generateChallengeArray(length, max){ | |
var arr = []; | |
for(var i = 0; i < length; i++){ | |
arr.push(Math.random()*max); | |
} | |
return arr; | |
} | |
function quickSort(arr){ | |
if(arr.length === 1 || arr.length === 0){ | |
return arr; | |
} | |
var greater = []; | |
var less = []; | |
for(var i = 1; i < arr.length; i++){ | |
if(arr[i] >= arr[0]) greater.push(arr[i]); | |
else less.push(arr[i]); | |
} | |
return arrayConcat(quickSort(less), arr[0], quickSort(greater)); | |
} | |
function arrayConcat(arr1, val, arr2){ | |
// This is faster than array.concat, because concat will allocate an entirely new array in memory | |
arr1.push(val); | |
for(var i = 0; i < arr2.length; i++){ | |
arr1.push(arr2[i]); | |
} | |
return arr1; | |
} | |
unsorted = generateChallengeArray(10000000, 1000); | |
console.log("generated"); | |
var time = Date.now(); | |
var arr = quickSort(unsorted); | |
console.log("That took " + (Date.now() - time)/1000 + " seconds"); | |
console.log("verifying..."); | |
for(var i = 1; i < arr.length; i++){ | |
if(arr[i] < arr[i-1]){ | |
console.log("FAILED!"); | |
} | |
} | |
console.log("PASSED!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment