Skip to content

Instantly share code, notes, and snippets.

@couto
Last active December 10, 2015 14:08
Show Gist options
  • Save couto/4445538 to your computer and use it in GitHub Desktop.
Save couto/4445538 to your computer and use it in GitHub Desktop.
/**
* QuickSort
*
* @param {Array} arr Array to be sorted
* @returns {Array} new array sorted
*/
var quickSort = function (arr) {
'use strict';
var sort = function (arr) {
var less = [],
greater = [],
pivot = arr.splice(Math.floor(arr.length/2), 1),
swapped = false;
arr.forEach(function (val) {
if (val < pivot) { less.push(val); }
else { greater.push(val); }
});
swapped = (less.length || greater.length);
return (swapped) ?
[].concat(sort(less))
.concat(pivot)
.concat(sort(greater)) :
[].concat(less)
.concat(pivot)
.concat(greater);
};
if (arr.length <= 1) { return arr; }
return sort(arr);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment