Skip to content

Instantly share code, notes, and snippets.

@kangax
Last active September 5, 2021 19:44
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save kangax/6c4407941d976fe00948 to your computer and use it in GitHub Desktop.
Save kangax/6c4407941d976fe00948 to your computer and use it in GitHub Desktop.
Haskell-inspired quick sort in ES6
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smallerSorted = quicksort (filter (<=x) xs)
biggerSorted = quicksort (filter (>x) xs)
in smallerSorted ++ [x] ++ biggerSorted
/*
1) passing array
> quicksort([4,3,2,1]); // => [1,2,3,4]
*/
function quicksort(tail) {
if (tail.length === 0) return [];
let head = tail.splice(0, 1)[0];
return quicksort(tail.filter( _ => _ <= head))
.concat([head])
.concat(quicksort(tail.filter( _ => _ > head )))
}
/*
2) via arguments
> quicksort(4,3,2,1); // => [1,2,3,4]
or:
> quicksort(...[4,3,2,1]); // => [1,2,3,4]
*/
function quicksort(x, ...xs) {
if (arguments.length === 0) return [];
return quicksort(...xs.filter( _ => _ <= x))
.concat([x])
.concat(quicksort(...xs.filter( _ => _ > x )))
}
@wjramos
Copy link

wjramos commented Apr 21, 2021

I like this one :)

const quicksort = array => {
    if (array.length === 0) return [];
    let [x, ...xs] = array;    
    return [
        ...quicksort(xs.filter(y => y < x)),
        x,
        ...quicksort(xs.filter(y => y >= x))
    ];
};

One issue is performance since you are filtering the same array twice

@wjramos
Copy link

wjramos commented Apr 21, 2021

function quickSort(values = []) {
  const [pivot, ...restValues] = values;
  
  if (!pivot) return [];
  if (!restValues.length) return [pivot];
  
  const [lesser, greater] = restValues.reduce((partitions, val) => {    
    partitions[+(val > pivot)].push(val);

    return partitions;
  }, [[], []]);
  
  return [
    ...quickSort(lesser),
    pivot,
    ...quickSort(greater),
  ];
}

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