Last active
August 6, 2023 15:14
-
-
Save codertcet111/2f969c45eeb6552c699f05c2df0e0b0f to your computer and use it in GitHub Desktop.
Quick sort recursively 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
| #Author: Shubham Mishra | |
| def quick_sort(arr) | |
| return arr if arr.length <= 1 | |
| # Choose the pivot element (for simplicity, we'll use the last element) | |
| pivot = arr.pop | |
| left = [] | |
| right = [] | |
| # Partition the array into two sub-arrays based on the pivot element | |
| arr.each do |element| | |
| if element <= pivot | |
| left << element | |
| else | |
| right << element | |
| end | |
| end | |
| # Recursive calls for the two sub-arrays | |
| sorted_left = quick_sort(left) | |
| sorted_right = quick_sort(right) | |
| # Combine the sorted sub-arrays and the pivot to form the final sorted array | |
| sorted_left + [pivot] + sorted_right | |
| end | |
| # Example usage: | |
| arr = [10, 7, 8, 9, 1, 5] | |
| sorted_arr = quick_sort(arr) | |
| puts sorted_arr.join(' ') | |
| ####Now lets check code when pivot element is selected as middle element: | |
| def quick_sort(arr) | |
| return arr if arr.length <= 1 | |
| # Choose the pivot element as the middle element | |
| pivot_index = arr.length / 2 | |
| pivot = arr[pivot_index] | |
| arr.delete_at(pivot_index) | |
| left = [] | |
| right = [] | |
| # Partition the array into two sub-arrays based on the pivot element | |
| arr.each do |element| | |
| if element <= pivot | |
| left << element | |
| else | |
| right << element | |
| end | |
| end | |
| # Recursive calls for the two sub-arrays | |
| sorted_left = quick_sort(left) | |
| sorted_right = quick_sort(right) | |
| # Combine the sorted sub-arrays and the pivot to form the final sorted array | |
| sorted_left + [pivot] + sorted_right | |
| end | |
| # Example usage: | |
| arr = [10, 7, 8, 9, 1, 5] | |
| sorted_arr = quick_sort(arr) | |
| puts sorted_arr.join(' ') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment