Skip to content

Instantly share code, notes, and snippets.

@reciosonny
Last active October 15, 2016 01:15
Show Gist options
  • Save reciosonny/95c07e9ba0b256d9f68fbd9716939f04 to your computer and use it in GitHub Desktop.
Save reciosonny/95c07e9ba0b256d9f68fbd9716939f04 to your computer and use it in GitHub Desktop.
quicksort algorithms
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])
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]));
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