R 蛮力选择排序

R 蛮力选择排序,r,brute-force,selection-sort,R,Brute Force,Selection Sort,我正在尝试编写R代码来执行蛮力选择排序。但是我不知道怎么写min,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):(

我正在尝试编写R代码来执行蛮力选择排序。但是我不知道怎么写min,
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
}
示例
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
}