如何有效地计算冒泡排序迭代的次数?

时间:2018-03-26 22:57:24

标签: algorithm performance sorting complexity-theory mergesort

典型的冒泡排序(复杂度为N ^ 2)看起来像这样(来自维基百科):

procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat
    swapped = false
    for i = 1 to n-1 inclusive do
        if A[i-1] > A[i] then
            swap( A[i-1], A[i] )
            swapped = true

如何确定外循环在 O(N ^ 2)中迭代的次数? (如下所示,它太慢了):

procedure bubbleSort( A : list of sortable items )
n = length(A)
count = 0
repeat
    count += 1
    swapped = false
    for i = 1 to n-1 inclusive do
        if A[i-1] > A[i] then
            swap( A[i-1], A[i] )
            swapped = true

1 个答案:

答案 0 :(得分:0)

每次迭代都会将最大的元素移动到数组的末尾(让我们从左到右);每个较小的元素将向左移动最多1个位置。所需外环的数量是该方向上任何数字的最大位移。

在更详细的术语中,您需要找到左侧具有最大数量的较大元素的数组元素。这个数量(“最大数量”)就是你的答案。

你能从那里拿走吗?