Last active
April 8, 2018 01:18
-
-
Save sanchojaf/762985f8d4e40c184714ed90e9e32f2f to your computer and use it in GitHub Desktop.
Ruby QuickSort and QuickSelect
This file contains 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 quicksort(arr, first, last) | |
return arr unless first < last | |
p_index = partition(arr, first, last) | |
quicksort(arr, first, p_index - 1) | |
quicksort(arr, p_index + 1, last) | |
arr | |
end | |
def quickselect(arr, first, last, i) | |
return arr[first] if first == last | |
p_index = partition(arr, first, last) | |
k = p_index - first + 1 | |
if i == k | |
arr[p_index] | |
elsif i < k | |
quickselect(arr, first, p_index - 1, i) | |
else | |
quickselect(arr, p_index + 1, last, i - k) | |
end | |
end | |
def partition(arr, first, last) | |
pivot = arr[last] | |
p_index = first | |
(first..last).each do |i| | |
if arr[i] <= pivot | |
arr[i], arr[p_index] = arr[p_index], arr[i] | |
p_index += 1 | |
end | |
end | |
arr[last], arr[p_index] = arr[p_index], pivot | |
p_index | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment