Skip to content

Instantly share code, notes, and snippets.

@RSNara
Last active December 30, 2015 06:46
Show Gist options
  • Save RSNara/82007bd39dd92b6eab79 to your computer and use it in GitHub Desktop.
Save RSNara/82007bd39dd92b6eab79 to your computer and use it in GitHub Desktop.
An flavour of quick-sort I found while reading "The joy of Clojure". In the book, the Clojure implementation was tail-recursive and lazy; this translation has neither of those qualities. It was written to help me understand the Clojure implementation.
console.log(quickSort([2,1,4,3]));
console.log(quickSort(randomInts(20)));
function randomInts(n) {
return Array.apply(null, Array(n)).map(() => Math.floor(Math.random() * n));
}
function quickSort(array) {
return quickSortLists([array]);
}
function quickSortLists(lists) {
const selectedList = first(lists);
const otherLists = rest(lists);
if (isNotEmpty(selectedList)) {
const pivot = first(selectedList);
const otherItemsInList = rest(selectedList);
return quickSortLists([
otherItemsInList.filter((item) => item < pivot),
pivot,
otherItemsInList.filter((item) => item >= pivot),
...otherLists
]);
} else if (isNotEmpty(otherLists)) {
return [ first(otherLists), ...quickSortLists(rest(otherLists)) ];
} else {
return [];
}
}
function isNotEmpty(list) {
return Array.isArray(list) && list.length !== 0;
}
function first(list) {
return list[0];
}
function rest(list) {
return list.slice(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment