Skip to content

Instantly share code, notes, and snippets.

@vaibhavtolia
Last active August 30, 2016 11:51
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vaibhavtolia/6747303 to your computer and use it in GitHub Desktop.
Save vaibhavtolia/6747303 to your computer and use it in GitHub Desktop.
Quick-Sort in javascript
function quickSort(a, low, high){
if(high > low){
var index = getRandomInt(low,high);
//console.log(low,high,index);
var pivot = a[index];
//console.log("pivot",pivot);
a = partition(a,pivot);
//console.log(a);
quickSort(a,low,index-1);
quickSort(a,index+1,high);
}
return a;
}
function partition (a,pivot) {
var i = 0;
for( var j=0; j < a.length; j++ ){
if( a[j]!= pivot && a[j] < pivot ){
var temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
}
}
return a;
}
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var arr = [1,3,455,45,32,23,345,43,2,23,234,34];
quickSort(arr,0,arr.length);
@Pinhead877
Copy link

I copy pasted it with the test array and it didnt sort it right
my ouput:

[1, 3, 2, 23, 32, 23, 34, 45, 234, 43, 345, 455]

@mayrascript
Copy link

Yes, that's algoritm is wrong

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment