Skip to content

Commit 1e2d586

Browse files
author
Leon Rische
committed
code for chapter 2 in ruby
1 parent a1a41e9 commit 1e2d586

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Finds the smallest value in an array
2+
def findSmallest(arr)
3+
# Stores the smallest value
4+
smallest = arr[0]
5+
# Stores the index of the smallest value
6+
smallest_index = 0
7+
# (1...n) is the same as (1..(n-1))
8+
(1...(arr.length)).each do |i|
9+
if arr[i] < smallest
10+
smallest = arr[i]
11+
smallest_index = i
12+
end
13+
end
14+
smallest_index
15+
end
16+
17+
# Sort array
18+
def selectionSort(arr)
19+
newArr = []
20+
(0...(arr.length)).each do |i|
21+
# Finds the smallest element in the array and adds it to the new array
22+
smallest = findSmallest(arr)
23+
newArr.push(arr.delete_at(smallest))
24+
end
25+
newArr
26+
end
27+
28+
# 'p obj' is the same as 'puts obj.inspect'
29+
p selectionSort([5, 3, 6, 2, 10])

0 commit comments

Comments
 (0)