你可以将冒泡排序表示为幺半群或半群吗?

haw*_*eye 5 sorting haskell monoids semigroup

给出以下用于冒泡排序的伪代码

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
Run Code Online (Sandbox Code Playgroud)

这是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)
}
Run Code Online (Sandbox Code Playgroud)

这是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
Run Code Online (Sandbox Code Playgroud)

是否有可能将其表述为幺半群或半群?

pig*_*ker 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'
Run Code Online (Sandbox Code Playgroud)

插入排序由.给出

isort :: Ord x => [x] -> OL x
isort = foldMap (OL . pure)
Run Code Online (Sandbox Code Playgroud)

因为插入正好将单个列表与另一个列表合并.(通过构建平衡树,然后执行相同的foldMap来给出Mergesort.)

这与bubblesort有什么关系?插入排序和bubblesort具有完全相同的比较策略.如果您将其绘制为由比较和交换框组成的排序网络,您可以看到这一点.在这里,数据向下流动,向框[n]的较低输入向左流:

| | | |
[1] | |
| [2] |
[3] [4]
| [5] |
[6] | |
| | | |
Run Code Online (Sandbox Code Playgroud)

如果按照上述编号给出的顺序执行比较,在/ slices中切割图表,则会得到插入排序:第一次插入不需要比较; 第二个需要比较1; 第三个2,3; 最后4,5,6.

但是,相反,如果你切入\ slice ...

| | | |
[1] | |
| [2] |
[4] [3]
| [5] |
[6] | |
| | | |
Run Code Online (Sandbox Code Playgroud)

......你正在做冒泡:先通过1,2,3; 第二关4,5; 最后一次传球6.