Skip to content

Commit f243bd4

Browse files
Add Selection Sort in Ruby (#5169)
1 parent b56b033 commit f243bd4

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

archive/r/ruby/selection-sort.rb

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
def selection_sort(numbers)
2+
# Handle missing or invalid input
3+
if numbers.nil? || numbers.strip.empty?
4+
return 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'
5+
end
6+
7+
# Split into an array and convert to integers
8+
unsorted_elements = numbers.split(',').map(&:strip).map(&:to_i)
9+
10+
# Validate array has at least 2 elements
11+
if unsorted_elements.length < 2
12+
return 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'
13+
end
14+
15+
# Make an array to store the sorted elements
16+
sorted_elements = []
17+
18+
# Iterate until the list of unsorted elements is emptu
19+
until unsorted_elements.empty?
20+
# Store the minimal value in a variable
21+
min_element = unsorted_elements.min
22+
23+
# Add the element at the end of the sorted elements array
24+
sorted_elements.push(min_element)
25+
26+
# Delete the minimal value from the unsorted elements array
27+
unsorted_elements.delete_at(unsorted_elements.index(min_element))
28+
end
29+
30+
# Return as comma-separated string
31+
sorted_elements.join(', ')
32+
end
33+
34+
puts selection_sort(ARGV[0])

0 commit comments

Comments
 (0)