Created
August 7, 2023 13:52
-
-
Save codertcet111/1e4ba5d69f09e2bb87222d70b829a2e8 to your computer and use it in GitHub Desktop.
merge sort recursively in ruby, Author: Shubham Mishra
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 merge_sort(arr) | |
# Base case: If the array has only one element or is empty, it is already sorted | |
return arr if arr.length <= 1 | |
# Divide the array into two halves | |
mid = arr.length / 2 | |
left_half = arr[0...mid] | |
right_half = arr[mid..] | |
# Recursively sort the two halves | |
left_sorted = merge_sort(left_half) | |
right_sorted = merge_sort(right_half) | |
# Merge the two sorted halves | |
merge(left_sorted, right_sorted) | |
end | |
def merge(left, right) | |
merged_array = [] | |
left_index = 0 | |
right_index = 0 | |
# Merge elements from the left and right arrays into the merged array in ascending order | |
while left_index < left.length && right_index < right.length | |
if left[left_index] <= right[right_index] | |
merged_array << left[left_index] | |
left_index += 1 | |
else | |
merged_array << right[right_index] | |
right_index += 1 | |
end | |
end | |
# Add any remaining elements from the left and right arrays | |
merged_array.concat(left[left_index..]) | |
merged_array.concat(right[right_index..]) | |
merged_array | |
end | |
# Example usage: | |
arr = [38, 27, 43, 3, 9, 82, 10] | |
sorted_arr = merge_sort(arr) | |
puts sorted_arr.join(', ') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment