考慮下面的僞代碼冒泡排序你可以將Bubble排序爲幺半羣或半羣嗎?
procedure bubbleSort(A : list of sortable items)
repeat
swapped = false
for i = 1 to length(A) - 1 inclusive do:
/* if this pair is out of order */
if A[i-1] > A[i] then
/* swap them and remember something changed */
swap(A[i-1], A[i])
swapped = true
end if
end for
until not swapped
end procedure
這裏是冒泡排序爲斯卡拉
def bubbleSort[T](arr: Array[T])(implicit o: Ordering[T]) {
import o._
val consecutiveIndices = (arr.indices, arr.indices drop 1).zipped
var hasChanged = true
do {
hasChanged = false
consecutiveIndices foreach { (i1, i2) =>
if (arr(i1) > arr(i2)) {
hasChanged = true
val tmp = arr(i1)
arr(i1) = arr(i2)
arr(i2) = tmp
}
}
} while(hasChanged)
}
這是Haskell的實現代碼:
bsort :: Ord a => [a] -> [a]
bsort s = case _bsort s of
t | t == s -> t
| otherwise -> bsort t
where _bsort (x:x2:xs) | x > x2 = x2:(_bsort (x:xs))
| otherwise = x:(_bsort (x2:xs))
_bsort s = s
是否有可能把它表述成幺半羣還是半羣?
你可以(例如)創建一個超過「有序集合」的monoid,並使用sort('sort。(++)')作爲monoid組合運算符,但「將bsort」制定爲monoid「不是對我來說很清楚 – josejuan