给出bubble-sort
的以下伪代码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
以下是Bubble Sort as Scala的代码
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
是否有可能将其表述为幺半群或半群?
答案 0 :(得分:21)
我正在使用网络连接不良的手机,但现在就去了。
tl; dr bubblesort是插入排序是具有合并的有序列表的幺半群的“捣蛋”。
有序列表形成一个幺半群。
newtype OL x = OL [x]
instance Ord x => Monoid (OL x) where
mempty = OL []
mappend (OL xs) (OL ys) = OL (merge xs ys) where
merge [] ys = ys
merge xs [] = xs
merge xs@(x : xs') ys@(y : ys')
| x <= y = x : merge xs' ys
| otherwise = y : merge xs ys'
插入排序由
给出isort :: Ord x => [x] -> OL x
isort = foldMap (OL . pure)
因为插入正好将单个列表与另一个列表合并。 (通过构建平衡树,然后执行相同的foldMap来给出Mergesort。)
这与bubblesort有什么关系?插入排序和bubblesort具有完全相同的比较策略。如果您将其绘制为由比较和交换框组成的排序网络,您可以看到这一点。在这里,数据向下流动,向框[n]的较低输入向左移动:
| | | |
[1] | |
| [2] |
[3] [4]
| [5] |
[6] | |
| | | |
如果按照上面编号给出的顺序进行比较,在/ slices中切割图表,就会得到插入排序:第一次插入不需要比较;第二个需要比较1;第三个2,3;最后4,5,6。
但是,如果你切入\ slice ...
| | | |
[1] | |
| [2] |
[4] [3]
| [5] |
[6] | |
| | | |
...你正在做冒泡:先通过1,2,3;第二关4,5;最后一次传球6。