簡體   English   中英

你可以將冒泡排序表示為幺半群或半群嗎?

[英]Can you formulate the Bubble sort as a monoid or 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

這是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

是否有可能將其表述為幺半群或半群?

我正在使用網絡連接不良的手機,但這里有。

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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM