作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我一直在尝试按降序进行 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;
}
}
>=
它会导致 C++ 中的段错误。
最佳答案
假设你有一个像 {1, 2}
这样的数组. previousElementIndex
将从 0
开始但是您的内部循环不会执行,因为第一个条件 previousElementIndex > 0
在这种情况下是错误的。这就是为什么您的元素卡在位置一的原因。要解决此问题,您必须更改 >
至>=
,但您还必须更改 previousElementIndex
的类型为 int
当它变为-1时处理。
关于c++ - 降序插入排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59515466/
序 大家好呀,我是summo,这次来写写我在上班空闲(摸鱼)的时候做的一个小网站的事。去年阿里云不是推出了个活动嘛,2核2G的云服务器一年只要99块钱,懂行的人应该知道这个价格在业界已经是非常良心了
我尝试根据给定的级别顺序(BFS 顺序)构造 BST。我知道这是可能的,但我不知道我该怎么写。问题是我必须使用 BFS 序列。所以,我不能在这里使用递归,我必须迭代地编写我的程序......我发现这有
我是一名优秀的程序员,十分优秀!