簡體   English   中英

冒泡排序中的交換次數

[英]Number of swaps in Bubble Sort

我有一個冒泡版本:

int i, j;  

for i from n downto 1 
{
    for j from 1 to i-1 
    { 
        if (A[j] > A[j+1])
            swap(A[j], A[j+1]) 
    } 
}

我想使用上面版本的冒泡排序來計算預期的掉期數量。 我使用的方法如下所示:

// 0 based index

float ans = 0.0;

for ( int i = 0; i < n-1; i++ )
{
    for ( int j = i+1; j < n; j++ ) {

        ans += getprob( a[i], a[j]); // computes probability that a[i]>a[j].
    }
}

我是正確的方式還是我錯過了什么?

獲得答案的最佳方法是運行冒泡排序算法本身並在swap()調用后包含一個計數器。 您的計算函數將(a)幾乎與排序本身一樣長(取決於swap()與getprob()的運行時間)和(b)在排序時忽略元素順序發生變化的點。

順便說一句,swap()調用的確切數量取決於你需要排序的數據 - 你有n *(n-1)/ 2次比較,其中任何一個都可能導致交換(平均而言,你需要一半的時間)交換比較的元素)。

也許這有幫助。 基本上,這提供了一個框架,用於在一組模擬數據集上運行氣泡排序並計算交換概率。

設這個概率= p然后,要找到預期的交換操作數,您需要在真實數據集上應用它。 設n為該數據集的大小。 然后預期數量= swapProbability * n * n

n * n之所以出現是因為冒泡排序具有n * n個預期操作。

float computeSwapProbability()
{
    int aNumSwaps = 0
    int aTotalNumberOfOperations = 0

    For all simulation datasets
    {


        int i, j;  

        for i from n downto 1 

        { 

            for j from 1 to i-1 

            { 
                aTotalNumberOfOperations++

                if (A[j] > A[j+1]) 
                {
                    swap(A[j], A[j+1]) 
                    aNumSwaps++
                }

            } 

        }
    }

    return (float)aNumSwaps/aTotalNumberOfOperations;
}

計算交換的最佳方法是在交換的if條件中包含計數器變量。

    int swapCount=0;

    for (i = 0; i < (length-1); ++i) {
      for (j = 0; j < (length-i-1); ++j) {
        if(array[j] > array[j+1]) {
          temp = array[j+1];
          array[j+1] = array[j];
          array[j] = temp;
          swapCount++;
        }
      }
    }

    printf("Swap count : %d" ,swapCount);

暫無
暫無

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

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