我制作了以下代碼,但不幸的是不起作用:
#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
提前致謝 !
uj5u.com熱心網友回復:
您的演算法存在一些相當重要的問題,代碼格式就是其中之一(請使用適當的縮進和空格以提高代碼可讀性)。
- 我不認為
all你認為它會做什么。看看?all一些例子。 - 我沒有看到您的代碼中發生任何交換。我也不明白
B. - 我不明白
Infs的目的。他們應該怎么做?
選擇排序演算法的直接 R 實作,例如here將導致
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/390455.html
上一篇:Rdevtools檢查win函式在curl::curl_fetch_memory(url,handle=h)中拋出錯誤:接收失敗:連接已重置
