Skip to content

Instantly share code, notes, and snippets.

@theanam
Last active September 29, 2015 09:40
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 theanam/22ab0e5f8114b22126c2 to your computer and use it in GitHub Desktop.
Save theanam/22ab0e5f8114b22126c2 to your computer and use it in GitHub Desktop.
Quick Sort algorithm in JavaScript (with a relatively bigger memory complexity, for demonstration purpose only)
var unsorted = [53,12,22,87,74,67,23,45,77,1,8,44];
function quickSort(arr){
if(arr.length<2)
return arr;
var smaller = [];
var larger = [];
var pivot = arr[Math.floor(Math.random()*arr.length)];
for(i=0;i<arr.length;i++){
if(arr[i]<=pivot)
smaller.push(arr[i])
else
larger.push(arr[i])
}
return quickSort(smaller).concat(quickSort(larger))
}
console.log(quickSort(unsorted))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment