Created
December 22, 2014 20:03
-
-
Save krg7880/92ad71c91ada44df3dda to your computer and use it in GitHub Desktop.
Javscript QuickSort
This file contains hidden or 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
| /** | |
| Quickly sorts elements using recursion | |
| Complexity: O(n^2) n-squared | |
| @param {Array} collection | |
| @return {Array} | |
| */ | |
| function quicksort(collection) { | |
| var i = 1; | |
| var n = collection.length; | |
| // first element of the collection | |
| // used to test other entries against. | |
| var pivot = null; | |
| var left = []; | |
| var right = []; | |
| var current = null; | |
| if (n <= 1) { | |
| return collection; | |
| } | |
| // assign first element of array | |
| pivot = collection[0]; | |
| for (i; i<n; i++) { | |
| current = collection[i]; | |
| if (current) { | |
| if (current < pivot) { | |
| left.push(current); | |
| } else { | |
| right.push(current); | |
| } | |
| } | |
| } | |
| // recursively break down the left and | |
| // right and sort them | |
| return quicksort(left).concat(pivot, quicksort(right)); | |
| } | |
| var names = ["Kate", "Ann", "Ricky", "Paul", "Mike", "Rose"]; | |
| console.log(quicksort(names)); | |
| var age = [100, 50, 200, 56, 76, 3]; | |
| console.log(quicksort(age)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment