首页 > 解决方案 > shell 排序函数中的交换和比较次数不正确

问题描述

我有一个任务,我必须创建一个函数来计算 shell 排序完成的交换和比较次数。但是,该函数为每个返回的数字非常大。我正在使用结构来保存交换和比较的值,但我认为我把它们放在了一个奇怪的地方。

struct SwapAndComp {
    long long swaps;
    long long comps;
};

SwapAndComp insertionSortInterleaved(long numbers[], long numbersSize, long startIndex, long gap, long long& swaps, long long& comps) {
    SwapAndComp shell;
    int i = 0;
    int j = 0;
    int temp = 0;  

    for (i = startIndex + gap; i < numbersSize; i = i + gap) {
        j = i;
        while (j - gap >= startIndex) {
            comps++;
            if (numbers[j] < numbers[j - 1]) {
                temp = numbers[j];
                numbers[j] = numbers[j - gap];
                numbers[j - gap] = temp;
                j = j - gap;
                swaps++;
            }
            else break;
        }
    }

    shell.swaps = swaps;
    shell.comps = comps;
    return shell;
}
SwapAndComp shellSort(long numbers[], long numbersSize, long gapArray[], long numGaps, long long& swaps, long long& comps) {
    SwapAndComp once;
    SwapAndComp total;
    for (int i = 0; i < numGaps; i++) {
        for (int j = 0; j < gapArray[i]; j++) {
            once = insertionSortInterleaved(numbers, numbersSize, j, gapArray[i], total.swaps, total.comps);
            total.swaps += once.swaps;
            total.comps += once.comps;
        }
    }
    return total;
}

我认为问题出在shell排序功能上。我正在尝试从每个 insertSortInterleaved 函数中添加所有交换和比较,但是当我以 5000 的数组大小在 main 中调用它时,我得到

外壳排序:时间:0.01 交换:-3814709954702659342 比较:-2522982850760493548

如您所见,我得到一个很大的负数。我不确定是不是因为循环超出了界限或什么,但这让我有点困惑。任何帮助,将不胜感激!谢谢!

标签: c++

解决方案


推荐阅读