c++ - 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
如您所见,我得到一个很大的负数。我不确定是不是因为循环超出了界限或什么,但这让我有点困惑。任何帮助,将不胜感激!谢谢!
解决方案
推荐阅读
- python - 如何以 GEOTIFF 格式保存图像?
- node.js - 简历解析器的节点js问题
- python - 模型导入的 Django Gunicorn Thread 问题
- html - 添加新值后我无法更新表格
- swift - 使用 ui 测试点击 WKWebview 内容
- react-native - 如何使用 react native 播放 scorm 文件?
- ansible - 如何在 ansible 云形成模块中传递参数文件
- svelte - 如何在 Svelte/Sapper 应用程序中包含 JQuery?
- c++ - C++ - 如何调试 SIGILL ILL_ILLOPN
- objective-c - 带有objective-c react-native的流屏幕