跟踪选择排序中的交换次数和比较

问题描述 投票:-1回答:1

我需要能够跟踪此选择排序算法中的交换次数和比较次数。该算法对数组进行了很好的排序。我需要修改它以跟踪交换的数量。

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++;
}
c++ function insertion-sort
1个回答
0
投票

那样的东西?

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
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.