Last active
August 1, 2018 03:57
-
-
Save CharmedSatyr/ac3bb89a5ac20781c08edbb577c199e3 to your computer and use it in GitHub Desktop.
Quick Sort implemented in JavaScript
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
/* Quick sort is an efficient, recursive divide-and-conquer | |
* approach to sorting an array. In this method, a pivot value | |
* is chosen in the original array. The array is then | |
* partitioned into two subarrays of values less than and | |
* greater than the pivot value. We then combine the result of | |
* recursively calling the quick sort algorithm on both | |
* sub-arrays. This continues until the base case of an empty | |
* or single-item array is reached, which we return. The | |
* unwinding of the recursive calls return us the sorted array. | |
*/ | |
const quickSort = array => { | |
// Return the array if it's too short to sort | |
if (array.length <= 1) { | |
return array; | |
} | |
// Otherwise, make a clean copy of the array | |
let arr = [...array]; | |
// Arbitrarily set last arr element as pivot value | |
const pivot = arr.pop(); | |
// Make empty arrays for values <= and > pivot value | |
const lessEq = []; | |
const greater = []; | |
// Loop through arr, separating values by comparison to pivot | |
arr.forEach(n => (n <= pivot ? lessEq.push(n) : greater.push(n))); | |
// Return recursively sorted values | |
return [...quickSort(lessEq), pivot, ...quickSort(greater)]; | |
}; | |
const even = [3, 5, 2, 6, 1, 9]; | |
const odd = [5, 8, 1, 9, 0, 7, 4]; | |
const dups = [4, 4, 8, 2, 0, 1, 2, 9]; | |
console.log('even:', quickSort(even)); // [ 1, 2, 3, 5, 6, 9 ] | |
console.log('odd:', quickSort(odd)); // [ 0, 1, 4, 5, 7, 8, 9 ] | |
console.log('dups:', quickSort(dups)); // [ 0, 1, 2, 2, 4, 4, 8, 9 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment