Skip to content

Instantly share code, notes, and snippets.

@mgechev
Last active November 13, 2015 05:59
Show Gist options
  • Save mgechev/04d50aa62abb94992e9b to your computer and use it in GitHub Desktop.
Save mgechev/04d50aa62abb94992e9b to your computer and use it in GitHub Desktop.
Quick sort with ECMAScript array comprehensions
(defn qs [lst]
(let [[head & tail] lst]
(if (>= 1 (count lst))
lst
(flatten [(qs (for [x tail :when (<= x head)] x)) head (qs (for [x tail :when (> x head)] x))]))))
-- Haskell implementation
quicksort [] = []
quicksort (x:xs) = smallerSorted ++ [x] ++ biggerSorted
let smallerSorted = quicksort [a | a <- xs, a <= x]
biggerSorted = quicksort [a | a <- xs, a > x]
// JavaScript implementation
let qs = (arr) => {
if (!arr || !arr.length) return [];
let pivot = arr.pop();
return qs([for (x of arr) if (x <= pivot) x])
.concat(pivot)
.concat(qs([for (y of arr) if (y > pivot) y]));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment