Created
May 3, 2011 13:19
-
-
Save brianstorti/953310 to your computer and use it in GitHub Desktop.
Selection Sort in ruby
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
# Selection sort (very slow on large lists) | |
a = [9,8,6,1,2,5,4,3,9,50,12,11] | |
n = a.size - 1 | |
n.times do |i| | |
index_min = i | |
(i + 1).upto(n) do |j| | |
index_min = j if a[j] < a[index_min] | |
end | |
# Yep, in ruby I can do that, no aux variable. w00t! | |
a[i], a[index_min] = a[index_min], a[i] if index_min != i | |
end |
great
def selection_sort(arr)
n = arr.length - 1
n.times do |i|
min_index = i
((i + 1)..n).each do |j|
min_index = j if arr[j] < arr[min_index]
end
arr[i], arr[min_index] = arr[min_index], arr[i] if min_index != i
end
arr
end
arr = [2, 5, 6, 2, 5425, 54, 5, 4, 12, 7, 3, 5, 5]
print selection_sort(arr)
Love it!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My ruby version of selection sort: