Created
September 11, 2017 19:13
-
-
Save Nitesh-Mishra/dd77488d00eb6a1efa334c422e14dc86 to your computer and use it in GitHub Desktop.
Quick Sort program in ruby
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
| # quick_sort.rb | |
| # | |
| # $ ruby quick_sort.rb | |
| # [1, 2, 3, 4, 5, 6, 7, 8] | |
| def quicksort(array) | |
| return array if array.length <= 1 | |
| pivot_index = (array.length / 2).to_i | |
| pivot_value = array[pivot_index] | |
| array.delete_at(pivot_index) | |
| lesser = [] | |
| greater = [] | |
| array.each do |x| | |
| if x <= pivot_value | |
| lesser << x | |
| else | |
| greater << x | |
| end | |
| end | |
| return quicksort(lesser) + [pivot_value] + quicksort(greater) | |
| end | |
| array = [6,5,3,1,8,7,2,4] | |
| sorted = quicksort(array) | |
| print sorted |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment