Last active
July 15, 2017 18:49
-
-
Save ricokareem/f78319639f056d0e7b2fd5e6de401539 to your computer and use it in GitHub Desktop.
JS Bin[simple quicksort algo]// source http://jsbin.com/wenayu
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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