【问题标题】:operations counting insertion bubble selection操作计数插入气泡选择
【发布时间】:2017-05-03 02:11:37
【问题描述】:

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

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;
}

【问题讨论】:

  • 你不应该在循环之前设置operations=0吗?现在,您只是在调用函数时添加 operations 的任何值,这可能是任何值。

标签: c++ insertion-sort


【解决方案1】:

参考这篇文章: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;
}

【讨论】:

  • 如果operations 输入了一个荒谬的数字,您的解决方案将不起作用。没有迹象表明 operations 在函数外被初始化。
  • 根据@PaulMcKenzie 的评论进行的更改。谢谢。
猜你喜欢
  • 2016-05-14
  • 2021-05-03
  • 2014-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
  • 1970-01-01
  • 2014-01-29
相关资源
最近更新 更多