鸡尾酒排序代码段错误 - 不知道为什么
我编写了一个鸡尾酒排序算法,并通过生成大小为 500 到 10,000 的随机向量来测试它 - 每个向量运行 10 次。在大约 2000-3000 长度的向量标记之后,代码出现段错误。我希望这不是测试代码,因为相同的测试用于多种排序算法,并且它对于其他所有算法都运行良好。我假设在某个地方我错过了一个结束条件,并且它尝试访问输入数组中不存在的元素......但我不完全确定这是否会导致运行段错误。
这是代码,我希望有人能发现我的错误。 (我也希望任何关于如何改进它的评论 - 但请注意,我确实更看重这段代码的可读性而不是速度。)
void Sorting::cocktailSort(vector<int>& A) {
int temp;
// The first/last indexes to check. Anything before/after these indexes
// is already sorted.
int firstIndex = -1;
int lastIndex = A.size()-1;
bool swapped;
do {
firstIndex += 1;
swapped = false;
for(int i = firstIndex-1; i < lastIndex; i++) {
if(A[i] > A[i+1]) {
temp = A[i];
A[i] = A[i+1];
A[i+1] = temp;
swapped = true;
}
}
if(!swapped) break;
swapped = false;
lastIndex -= 1;
for(int i = lastIndex; i >= firstIndex; i--) {
if(A[i] < A[i-1]) {
temp = A[i];
A[i] = A[i-1];
A[i-1] = temp;
swapped = true;
}
}
}while (swapped);
}
这不是家庭作业。
I wrote a Cocktail Sort algorithm, and am testing it by generating random vectors of size 500 up to 10,000 - running it 10 times per vector. After about the 2000-3000 length vector mark, the code segfaults. I expect it isn't the test code as the same test is used for multiple sorting algorithms and it runs fine for every other algorithm. I am assuming somewhere I miss an end-condition and it tries to access an element of the input array that doesn't exist... but I'm not entirely sure if that would cause a segfault to be run.
This is the code, I hope someone can spot my error. (I also would enjoy any comments on how it could be better - but please note I do value readability over speed for this code.)
void Sorting::cocktailSort(vector<int>& A) {
int temp;
// The first/last indexes to check. Anything before/after these indexes
// is already sorted.
int firstIndex = -1;
int lastIndex = A.size()-1;
bool swapped;
do {
firstIndex += 1;
swapped = false;
for(int i = firstIndex-1; i < lastIndex; i++) {
if(A[i] > A[i+1]) {
temp = A[i];
A[i] = A[i+1];
A[i+1] = temp;
swapped = true;
}
}
if(!swapped) break;
swapped = false;
lastIndex -= 1;
for(int i = lastIndex; i >= firstIndex; i--) {
if(A[i] < A[i-1]) {
temp = A[i];
A[i] = A[i-1];
A[i-1] = temp;
swapped = true;
}
}
}while (swapped);
}
This is not homework.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果使用 A.at(i) 而不是 A[i],则会进行边界检查,并抛出超出范围的异常。这可能有助于调试。
在我看来,当firstIndex为零(主循环的第一次迭代)时,这里的访问...
将出界。
If you use A.at(i) instead of A[i], bounds checking will be done, and out-of-range exceptions thrown. That may be helpful for debugging.
It appears to me that the access here...
will be out-of-bounds when firstIndex is zero (the first iteration of the main loop).
这可能对你有帮助
This may help you