【问题标题】:Insertion Sort Algorithm on Reverse Ordered Array Costs 0.00000 seconds?逆序数组的插入排序算法花费 0.00000 秒?
【发布时间】:2017-03-19 17:54:49
【问题描述】:

我在数组中随机创建了 30.000 个数字。然后我正常排序这些数字。之后,我反转,并应用插入排序算法。看看;

 begin = clock();
 insertion(dizi, boyut);
 end = clock();

 printf("\n time cost: %f z... ", (double)(end - begin) / CLOCKS_PER_SEC);

当我打印时,它显示 0.000000 秒,这是不可能的。 我哪里做错了?

这是我的插入排序代码

void insertion(int dizi[], int boyut)
{
    int i, j, temp;

    for(i = 1; i < boyut; i++)
    {
        temp = dizi[i];
        j = i-1;
        while((temp < dizi[j] && j >= 0))
        {
            dizi[j+1] = dizi[j];
            j--;
        }
        dizi[j+1] = temp;
    }
}

【问题讨论】:

  • 问题是什么?
  • 我的代码可能有错误,我看不到。我需要建议,谢谢。
  • 检查j&gt;=0 之前 dizi[j]...但这不是您要寻找的问题
  • stackoverflow.com/questions/11227809/… 这个答案也适用于反向排序的数组。

标签: algorithm sorting


【解决方案1】:

这个错误很微妙:编译器观察到您对该数组进行了大量写入,但随后从未对其进行任何操作,因此它有助于删除该部分以使您的代码运行得更快。在这种情况下,速度要快得多。

为了解决这个问题,在对数据进行排序后,从数组中打印一个随机元素,以便“使用”数据。如果打印一个随机元素,编译器知道它实际上需要对整个数组进行排序,并且不能作弊。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    相关资源
    最近更新 更多