Created
October 21, 2015 23:36
-
-
Save bootcoder/aa4e873d77bade957927 to your computer and use it in GitHub Desktop.
Sample of Quick sort
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
| def quicksort(array, from=0, to=nil) | |
| if to == nil | |
| # Sort the whole array, by default | |
| to = array.count - 1 | |
| end | |
| if from >= to | |
| # Done sorting | |
| return | |
| end | |
| # Take a pivot value, at the far left | |
| pivot = array[from] | |
| # Min and Max pointers | |
| min = from | |
| max = to | |
| # Current free slot | |
| free = min | |
| while min < max | |
| if free == min # Evaluate array[max] | |
| if array[max] <= pivot # Smaller than pivot, must move | |
| array[free] = array[max] | |
| min += 1 | |
| free = max | |
| else | |
| max -= 1 | |
| end | |
| elsif free == max # Evaluate array[min] | |
| if array[min] >= pivot # Bigger than pivot, must move | |
| array[free] = array[min] | |
| max -= 1 | |
| free = min | |
| else | |
| min += 1 | |
| end | |
| else | |
| raise "Inconsistent state" | |
| end | |
| end | |
| array[free] = pivot | |
| quicksort array, from, free - 1 | |
| quicksort array, free + 1, to | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment