Skip to content

Conversation

star1327p
Copy link
Contributor

added selection sort for R

@cyrusmsk
Copy link
Contributor

I have almost identical code:

# it is possible to use which.min(arr)
find_smallest <- function(arr) {
    smallest <- arr[1]
    smallest_index <- 1
    for(i in 1:length(arr)) {
        if (smallest > arr[i]) {
            smallest <- arr[i]
            smallest_index <- i
        }
    }
    smallest_index
}

selection_sort <- function(arr) {
    newArr <- c()
    for(i in 1:(length(arr))) {
        smallest <- find_smallest(arr) # which.min(arr)
        newArr <- append(newArr, arr[smallest])
        arr <- arr[-smallest]
    }
    newArr
}

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

@egonSchiele egonSchiele merged commit ceea225 into egonSchiele:master May 1, 2025
@egonSchiele
Copy link
Owner

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants