Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions 02_selection_sort/R/01_selection_sort.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Finds the smallest value in an array
find_smallest <- function(arr) {
# Stores the smallest value
smallest = arr[1]
# Stores the index of the smallest value
smallest_index = 1
for (i in 1:length(arr)) {
if (arr[i] < smallest) {
smallest_index = i
smallest = arr[i]
}
}
return(smallest_index)
}

# Sort array
selection_sort <- function(arr) {
newArr = c()
for (i in 1:length(arr)) {
# Finds the smallest element in the array and adds it to the new array
smallest = find_smallest(arr)
newArr = c(newArr, arr[smallest])
# Removes that smallest element from the original array
arr = arr[-smallest]
}
return(newArr)
}

print(selection_sort(c(5, 3, 6, 2, 10)))