计算插入气泡选择的操作

时间:2017-05-03 02:11:38

标签: c++ insertion-sort

我似乎无法弄清楚我的代码是什么问题,我的插入排序代码得到了大量的操作。希望得到一些帮助。

int insertionSort(int arr[], int n, int &operations)
{
    clock_t start = clock(); 
    int i, key, j;
    for (i = 1; i < n; i++) 
    {
        key = arr[i];
        j = i - 1;

        while (j >= 0 && arr[j] > key)
        {
            arr[j + 1] = arr[j];
            j = j - 1;
            operations++;
        }
        arr[j + 1] = key;
    }
    clock_t end = clock(); 
    return end - start;
}

1 个答案:

答案 0 :(得分:0)

参考这篇文章:How to count comparisons and swaps in insertion sort? (JAVA)

您可以将操作次数计算为:

long int operations=0;
int insertionSort(int arr[], int n, int &operations)
{
    clock_t start = clock(); 
    int i, key, j;
    for (i = 1; i < n; i++) 
    {
        key = arr[i];
        j = i - 1;

        while (1)
        {   
            operations++;
            if((j>=0) && (arr[j]>key)){
                arr[j + 1] = arr[j];
                j = j - 1;
             }
            else break;
        }
        arr[j + 1] = key;
    }
    clock_t end = clock(); 
    return end - start;
}