Home > OS >  simple loop, 2 indices (SelectionSort algorithm) for sorting an array
simple loop, 2 indices (SelectionSort algorithm) for sorting an array

Time:12-23

i’ve made the following code that unfortunately doesn’t work :

#scan the numbers,identify the min ,save it as the first element of
 #the output, repeat 

    Select <- function(n) {
     B <- rep(99,length(n)) #output array, same length as n 
    repeat {
 for (j in 1:length(n)) { 
for (i in 1:length(n)) { 
if (all(n[i]<=n)) {B[j] <- n[i] #if n[i] is the smallest in the #array, save it as B[j] 
n[i] <- Inf } #taking n[i] off the game
 }
 }
 if (all(n==Inf)) {return(B)} #if all are Inf then we're done, else.. #repeat
 } 
} 

(I tried to be as explainatory as possible) I also added a picture since it's not copied correctly in here : imgur.com/0a3vVO4

thanks in advance !

CodePudding user response:

There are some fairly significant issues with your algorithm, code formatting being one of them (please use proper indentation and whitespacing for code readability).

  1. I don't think all does what you think it does. Have a look at ?all for some examples.
  2. I don't see any swapping happening in your code. Nor do I understand the purpose of B.
  3. I don't understand the purpose of the Infs. What are they supposed to do?

A straightforward R implementation of the selection sort algorithm from e.g. here would lead to

ssort <- function(x) {
    for (i in 1:(length(x) - 1)) {
        min_index <- i
        for (j in (i   1):length(x)) if (x[j] < x[min_index]) min_index = j
        temp <- x[i]
        x[i] <- x[min_index]
        x[min_index] <- temp
    }
    x
}

Let's test

set.seed(2020)
identical(sort(x), ssort(x))
#[1] TRUE
  • Related