Skip to content

Instantly share code, notes, and snippets.

@falkirks
Created August 19, 2016 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save falkirks/0897438318a53c1d475860de32f3532f to your computer and use it in GitHub Desktop.
Save falkirks/0897438318a53c1d475860de32f3532f to your computer and use it in GitHub Desktop.
Bored on a bus...
// 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