Skip to content

Commit ceea225

Browse files
authored
added selection sort for R (egonSchiele#301)
1 parent f6932ee commit ceea225

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Finds the smallest value in an array
2+
find_smallest <- function(arr) {
3+
# Stores the smallest value
4+
smallest = arr[1]
5+
# Stores the index of the smallest value
6+
smallest_index = 1
7+
for (i in 1:length(arr)) {
8+
if (arr[i] < smallest) {
9+
smallest_index = i
10+
smallest = arr[i]
11+
}
12+
}
13+
return(smallest_index)
14+
}
15+
16+
# Sort array
17+
selection_sort <- function(arr) {
18+
newArr = c()
19+
for (i in 1:length(arr)) {
20+
# Finds the smallest element in the array and adds it to the new array
21+
smallest = find_smallest(arr)
22+
newArr = c(newArr, arr[smallest])
23+
# Removes that smallest element from the original array
24+
arr = arr[-smallest]
25+
}
26+
return(newArr)
27+
}
28+
29+
print(selection_sort(c(5, 3, 6, 2, 10)))
30+

0 commit comments

Comments
 (0)