我在R語言上做了一些編程工作來完成氣泡排序。有時它完美地工作,沒有任何錯誤消息,但有時,它顯示「錯誤在if(x [i]> x [i + 1]){:參數的長度爲零」。任何人都可以幫我檢查它有什麼問題嗎?我附上我的代碼如下R語言中的氣泡排序代碼中的錯誤消息
example <- function(x) {
n <- length(x)
repeat {
hasChanged <- FALSE
n <- n - 1
for(i in 1:n) {
if (x[i] > x[i+1]) {
temp <- x[i]
x[i] <- x[i+1]
x[i+1] <- temp
hasChanged <- TRUE
cat("The current Vector is", x ,"\n")
}
}
if (!hasChanged) break;
}
}
x <-sample(1:10,5)
cat("The original Vector is", x ,"\n")
example(x)
您是否考慮過使用'traceback'來確定哪個函數調用得到不正確的輸入?你應該得到那些無用的空行。 –