gpt4 book ai didi

c++ - 降序插入排序

转载 作者:行者123 更新时间:2023-12-02 10:22:28 25 4
gpt4 key购买 nike

我一直在尝试按降序进行 InsertionSort,但一直失败得很惨。

下面是我写的代码

void InsertionSortInDecrementing(int arr[], const size_t size) {
for (size_t i = 1; i < size; ++i) {
int currentElement = arr[i];
size_t previousElementIndex = i - 1;
while (previousElementIndex > 0 && currentElement > arr[previousElementIndex]) {
arr[previousElementIndex + 1] = arr[previousElementIndex];
--previousElementIndex;
}
arr[previousElementIndex + 1] = currentElement;
}
}

对于示例数组,最大元素确实向左移动,但最大元素卡在位置 1 并且不会移动到位置 0,如果我将 while 语句中的条件更改为 >=它会导致 C++ 中的段错误。

将不胜感激任何帮助!谢谢

最佳答案

假设你有一个像 {1, 2} 这样的数组. previousElementIndex将从 0 开始但是您的内部循环不会执行,因为第一个条件 previousElementIndex > 0在这种情况下是错误的。这就是为什么您的元素卡在位置一的原因。要解决此问题,您必须更改 >>= ,但您还必须更改 previousElementIndex的类型为 int当它变为-1时处理。

关于c++ - 降序插入排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59515466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com