Skip to content

Commit f29fca4

Browse files
authored
Implement Selection Sort in Ruby (#6)
* Create selection_sort.rb * Update README.md
1 parent 16357a3 commit f29fca4

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

Algorithms/selection_sort.rb

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Selection Sort Algorithm
2+
#
3+
# This algorithm sorts an array by repeatedly finding the minimum element from the unsorted part and putting it at the beginning.
4+
#
5+
# Parameters:
6+
# - array: The array to be sorted.
7+
#
8+
# Returns:
9+
# - The sorted array.
10+
11+
def selection_sort(array)
12+
n = array.size
13+
(0...n-1).each do |i|
14+
min_index = i
15+
(i+1...n).each do |j|
16+
min_index = j if array[j] < array[min_index]
17+
end
18+
array[i], array[min_index] = array[min_index], array[i] if min_index != i
19+
end
20+
array
21+
end
22+
23+
def test_selection_sort
24+
array = [64, 34, 25, 12, 22, 11, 90]
25+
sorted_array = selection_sort(array)
26+
puts "Sorted array: #{sorted_array}"
27+
end
28+
29+
test_selection_sort

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ Algorithms, Data Structures and resolution of programming questions.
4545
<summary>Selection Sort</summary>
4646

4747
- [C](https://github.com/mateuseap/Algorithms/blob/master/Algorithms/selectionSort.c)
48+
- [Ruby](https://github.com/mateuseap/Algorithms/blob/master/Algorithms/selection_sort.rb)
4849
</details>
4950

5051
### 🗃️ Data Structures:

0 commit comments

Comments
 (0)