r-简单循环,2个索引(SelectionSort算法),用于对数组进行排序



我制作了以下代码,但不幸的是,这些代码不起作用:

#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
} 
} 

(我尽量解释(我还添加了一张图片,因为它没有正确复制到这里:imgur.com/0a3vVO4

提前感谢!

您的算法存在一些相当严重的问题,代码格式就是其中之一(为了代码可读性,请使用适当的缩进和空格(。

  1. 我不认为all会像你认为的那样。请参阅?all中的一些示例
  2. 我看不到您的代码中发生任何交换。我也不理解B的目的
  3. 我不明白Inf的目的。他们应该做什么

这里的选择排序算法的直接R实现将导致

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
}

让我们测试

set.seed(2020)
x <- round(runif(10, min = 0, max = 10))
identical(sort(x), ssort(x))
#[1] TRUE

最新更新