Hits: 714
氣泡排序法 (Bubble sorting)
氣泡排序法 (bubble sorting) 就是相臨資料互相比較,若發現資料順序不對,就將資料互換,直到完成為止。先前在我的另外一篇文章有整理過 python 的寫法,這邊整理一下 R 的寫法
bubble <- function(list) {
len <- length(list)
switch <- TRUE
while (switch == TRUE) {
switch <- FALSE
for (i in 1:(len - 1)) {
if (list[i] > list[i + 1]) { # > for ascending, < for descending
list[c(i, i + 1)] <- list[c(i + 1, i)]
switch <- TRUE
}
result <- list
}
}
return(result)
}
來看看結果吧
> bubble(c(6,2,5,3,9))
[1] 2 3 5 6 9
> bubble(c(5,1,7,9,10,11,2,20,8,17,0))
[1] 0 1 2 5 7 8 9 10 11 17 20
解法說明
- 在第3行給定一個變數
switch == TRUE
,確保第5行開始的 while 迴圈能夠持續進行。 - 在 while 迴圈的一開始(第6行)就設定
switch == FALSE
,接下來第7行開始就是排序比較,只要指標i
的值大於指標i+1
的值,就把這兩個值交換,接下來設定switch == TRUE
並回到 while 迴圈的一開始。 - 接下來就讓迴圈持續的執行,當執行到沒有值好交換的時候,
switch == FALSE
就會讓迴圈結束,並回傳 result 這個我已經排序好的變數。
Comments