簡體   English   中英

跟蹤選擇排序中的交換和比較次數

[英]Track number of swaps and comparisons in selection sort

我需要能夠在此選擇排序算法中跟蹤交換和比較的數量。 該算法對數組進行排序就好了。 我需要修改它以跟蹤交換的數量。

void insertion_sort(int * theArray, int size)
{
   int tmp;
   for (int i = 1; i < size; i++) 
   {
        for (int j = i; j > 0 && theArray[j - 1] > theArray[j]; j--) 
        {
        tmp = theArray[j];
        theArray[j] = theArray[j - 1];
        theArray[j - 1] = tmp;
        }
    }
}

這是兩個輔助函數

bool inOrder(int i, int j) {
   numComparisons++;
   return i <= j;
}


void swapElement(int & i, int & j) {
    int t = i;
    i = j;
    j = t;
    numSwaps++;
}

類似的東西?

void insertion_sort(int * theArray, int size)
{
   int tmp;
   int count = 0;
   for (int i = 1; i < size; i++) 
   {
        for (int j = i; j > 0 && theArray[j - 1] > theArray[j]; j--) 
        {
        tmp = theArray[j];
        theArray[j] = theArray[j - 1];
        theArray[j - 1] = tmp;
        count++; // increment on each loop/exchanges
        }
    }
}

暫無
暫無

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

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