【问题标题】:Count the number of comparisons and permutations by round and the summation of the sorting algorithm按轮数计算比较次数和排列次数以及排序算法的总和
【发布时间】:2022-01-16 07:06:07
【问题描述】:
void sort(int a[], int n)
{
    for (int i = n - 2; i ≥ 0; i--)
    {
        int temp = a[i];
        int j;
        for (j = i + 1; j < n; j++)
        {
            if (a[j] > temp)
                a[j - 1] = a[j];
            else
                break;
        }
        a[j - 1] = temp;
    }
}

按轮数计算比较和排列的次数以及排序算法与a的总和:{4, 7, 12, 7, 1, 12}

【问题讨论】:

  • 计算排列数是什么意思?你能举一个输入和预期输出的例子吗?
  • 你还没有问过问题。

标签: c++ sorting


【解决方案1】:

您可以使用辅助变量来做到这一点:

void sort(int a[], int n)
{
    int outerLoop = 0;
    int comparisons = 0;
    for (int i = n - 2; i ≥ 0; i--)
    {
        outerLoop++;
        int temp = a[i];
        int j;
        for (j = i + 1; j < n; j++)
        {
            comparisons++;
            if (a[j] > temp)
                a[j - 1] = a[j];
            else
                break;
        }
        a[j - 1] = temp;
    }
    //Do something with outerLoop and comparisons...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多