我正在尝试写R代码来做暴力力量选择排序。但是我不知道怎么写min<- i和min<-j部分。
example <- function(x)
{
for (i in 1:(length(x)-1))
{
#min <- i
for (j in (i+1):(length(x)))
{
if (x[j] < x[(which.min(x))])
{
#min <- j
}
temp <- x[which.min(x)]
x[which.min(x)] <- x[i]
x[i] <- temp
}
}
x
}
x <-sample(1:100,10)
example(x)有人能帮我完成“#”部分吗?
我还附上了伪代码

发布于 2016-03-18 11:06:57
min是下一个最小元素的索引。因此,这与使用没有内部循环的which.min是一样的。
example <- function(x) {
for (i in 1:(length(x)-1)) {
mindex <- i # or, mindex <- which.min(x[(i+1):length(x)]) and remove the next loop
for (j in (i+1):(length(x))) {
if (x[j] < x[mindex])
mindex <- j
}
## swap
temp <- x[i]
x[i] <- x[mindex]
x[mindex] <- temp
}
x
}https://stackoverflow.com/questions/36075326
复制相似问题