Skip to content

Instantly share code, notes, and snippets.

@pixelsnob
Last active September 16, 2018 23:22
Show Gist options
  • Save pixelsnob/975839397e132dcaf4f669429bda2b6a to your computer and use it in GitHub Desktop.
Save pixelsnob/975839397e132dcaf4f669429bda2b6a to your computer and use it in GitHub Desktop.
function quicksort([ ...arr ]) {
if (!arr.length) {
return [];
}
let left = [], pivot = arr[0], right = [];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return [ ...quicksort(left), pivot, ...quicksort(right) ];
}
function quicksortCheck(array) {
var sortedArray = array.slice(0);
if(sortedArray.length == 0) return [];
var left = [], right = [], pivot = sortedArray[0];
for (var i = 1; i < sortedArray.length; i++) {
if(sortedArray[i] < pivot) {
left.push(sortedArray[i]);
} else {
right.push(sortedArray[i]);
}
}
return [ ...quicksortCheck(left), pivot, ...quicksortCheck(right) ];
}
const arr1 = [ 500, 4, 1, 5, 11, 90, 1100 ];
const arr2 = [ 1, 2, 3, 4 ];
const arr3 = [ 5, 9, 1, 0, 7, 10, 99 ];
console.log(quicksortCheck(arr1), quicksort(arr1));
console.log(quicksortCheck(arr2), quicksort(arr2));
console.log(quicksortCheck(arr3), quicksort(arr3));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment