Skip to content

added selection sort for R #301

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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)))