Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Last active July 15, 2017 17:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattpodwysocki/5414036 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/5414036 to your computer and use it in GitHub Desktop.
Implementation of QuickSort using ES6 features
// Using comprehensions
function sort(arr) {
var pivot, t;
if (arr.length === 0) {
return [];
}
[pivot, t] = [arr[0], arr.slice(1)];
return sort([x for (x of t) if x < pivot])
.concat(pivot)
.concat(sort([x for (x of t) if x >= pivot]));
}
// Using arrows with filter
function sort(arr) {
var pivot, t;
if (arr.length === 0) {
return [];
}
[pivot, t] = [arr[0], arr.slice(1)];
return sort(t.filter(x => x < pivot))
.concat(pivot)
.concat(sort(t.filter(x => x >= pivot)));
}
// Erlang equivalent
sort([Pivot|T]) ->
sort([ X || X <- T, X < Pivot]) ++
[Pivot] ++
sort([ X || X <- T, X >= Pivot]);
sort([]) -> [].
@domenic
Copy link

domenic commented Apr 18, 2013

[x for (x of t) if x < pivot]
t.filter(x => x < pivot)

hmm...

@mattpodwysocki
Copy link
Author

Sure, I suppose I could have used arrow functions with filter for each instead of comprehensions

@mattpodwysocki
Copy link
Author

Updated with alternate version. A better way of destructuring though?

@EggDice
Copy link

EggDice commented Jan 14, 2014

you don't really need concat neater.

function sort(arr) {
    if (!arr.length) {
        return [];
    }
    let pivot = arr.pop();
    return [
         ...sort([x for (x of arr) if x < pivot]),
         pivot,
         ...sort([x for (x of arr) if x >= pivot])
    ]
}

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