Created
June 3, 2015 14:14
-
-
Save fogonthedowns/2f6a5757c79f95d45415 to your computer and use it in GitHub Desktop.
Ruby 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
# The steps are: | |
# 1. Pick an element, called a pivot, from the array. | |
# 2. Reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with # # values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in # its final position. This is called the partition operation. | |
# 3. Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of # elements with greater values. | |
class Array | |
def quicksort | |
return [] if empty? | |
# 1 | |
pivot = delete_at(rand(size)) | |
# 2 | |
left, right = partition(&pivot.method(:>)) | |
# 3 | |
return *left.quicksort, pivot, *right.quicksort | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment