Last active
August 30, 2016 11:51
-
-
Save vaibhavtolia/6747303 to your computer and use it in GitHub Desktop.
Quick-Sort in javascript
This file contains 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
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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]