Last active
October 15, 2016 01:15
-
-
Save reciosonny/95c07e9ba0b256d9f68fbd9716939f04 to your computer and use it in GitHub Desktop.
quicksort algorithms
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
quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater) | |
where | |
lesser = filter (< p) xs | |
greater = filter (>= p) xs | |
main = do print(quicksort [4,3,2,1]) |
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(arr) { | |
if (arr.length < 2) { | |
return arr; | |
} else { | |
var pivot = arr[0]; | |
var less = []; | |
var greater = []; | |
var result = []; | |
for (var i = 1; i < arr.length; i++) { //skip first array | |
var j = arr[i]; | |
if (j <= pivot) { | |
less.push(j); | |
} else if (j > pivot) { | |
greater.push(j); | |
} | |
} | |
return quicksort(less) + [pivot] + quicksort(greater); | |
} | |
} | |
console.log(quicksort([10,5,2,3,7,4])); |
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
def quicksort(array): | |
# print(array) | |
if len(array) < 2: | |
return array #Base case: arrays with 0 or 1 element are already “sorted.” | |
else: | |
pivot = array[0] #Recursive case | |
less = [i for i in array[1:] if i <= pivot] #Sub-array of all the elements less than the pivot | |
greater = [i for i in array[1:] if i > pivot] #Sub-array of all the elements greater than the pivot | |
# print (less) | |
# print (greater) | |
result = quicksort(less) + [pivot] + quicksort(greater) | |
print(result) | |
return result | |
print (quicksort([10, 10,5, 2, 3])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment