Last active
April 12, 2019 17:30
-
-
Save omedale/7af9981a094e93bb235cffc470c4b818 to your computer and use it in GitHub Desktop.
Ruby Implementation 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 quick_sort(array) | |
| return array if array.size <= 1 | |
| # select a pivot element | |
| # here we get the first element of the array | |
| pivot ||= array.shift | |
| #use the pivot to break down the array into 2 subarray(left and right) | |
| left = array.select { |n| n < pivot } | |
| right = array.select { |n| n >= pivot } | |
| # recursively call quick_sort with the left and right array | |
| # then pick a pivot | |
| # if pivot is larger than the value to the right | |
| # switch their positions. | |
| return [*quick_sort(left), pivot, *quick_sort(right)] | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment