Skip to content

Instantly share code, notes, and snippets.

@ricokareem
Last active July 15, 2017 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricokareem/f78319639f056d0e7b2fd5e6de401539 to your computer and use it in GitHub Desktop.
Save ricokareem/f78319639f056d0e7b2fd5e6de401539 to your computer and use it in GitHub Desktop.
JS Bin[simple quicksort algo]// source http://jsbin.com/wenayu
function quickSort(data) {
if (data.length < 1) {
return [];
}
var left = [];
var right = [];
var pivot = data[0];
for (var i=1; i<data.length; i++) {
if (data[i] < pivot) {
left.push(data[i]);
} else {
right.push(data[i]);
}
}
return [].concat(quickSort(left), pivot, quickSort(right));
}
// From - https://gist.github.com/mattpodwysocki/5414036
// 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)));
}
// and finally
function sort(arr) {
if (!arr.length) {
return [];
}
let pivot = arr.pop();
return [
...sort(arr.filter(x => x < pivot)),
pivot,
...sort(arr.filter(x => x >= pivot))
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment