虽然它可能像其他人所说的那样是堆栈溢出,但我对此表示怀疑。您的代码有一些错误可能导致它访问数组中的超出范围的位置,这将(可能,但不能保证)提示提前终止分段错误(或者在其他情况下它似乎工作正常,这就是为什么 UB太糟糕了)。
考虑一下:
while(numberList[indexLow] <= numberList[pivot]){
indexLow++;
}
while(numberList[indexHigh] > numberList[pivot]){
indexHigh--;
}
如果数组中的每个数字都已经小于或等于numberList[pivot] 怎么办? indexLow 将愉快地递增超过 high,这很可能是数组的大小。您需要检查两个循环是否仍然存在外部循环条件。所以,改为这样做:
while (indexLow < indexHigh && numberList[indexLow] <= numberList[pivot]) {
indexLow++;
}
while (indexHigh > indexLow && numberList[indexHigh] > numberList[pivot]) {
indexHigh--;
}
这确保了内部循环不会使外部条件无效;没有这个,所有关于你的代码为什么会破坏/不工作的赌注都没有了。
然后我们有这个:
temp = numberList[pivot];
numberList[pivot] = numberList[indexHigh];
numberList[indexHigh] = temp;
现在,如果您按照我所说的那样修复循环,这可能会出现问题。循环可能已经停止,因为每个元素都小于或等于枢轴(在这种情况下,执行此交换操作是安全的),但循环可能已经停止,因为 indexLow 和 indexHigh 发生碰撞,并且在那如果我们不知道numberList[indexLow] 是否实际上大于枢轴,或者它是否仍然小于或等于枢轴。所以我们需要手动测试它,并可能减少 indexLow 以找到与枢轴交换的值:
assert(indexLow == indexHigh);
assert(indexLow > low);
if (numberList[indexLow] > numberList[pivot])
indexLow--;
assert(numberList[indexLow] <= numberList[pivot]);
temp = numberList[pivot];
numberList[pivot] = numberList[indexLow];
numberList[indexLow] = temp;
quickSort(numberList, low, indexLow-1);
quickSort(numberList, indexLow+1, high);
这是包含这些修复的完整版本:
void quickSort(vector<long> &numberList, long low, long high) {
long pivot, indexLow, indexHigh, temp;
if (low<high) {
pivot = low;
indexLow = low;
indexHigh = high;
while (indexLow < indexHigh) {
while (indexLow < indexHigh && numberList[indexLow] <= numberList[pivot]) {
indexLow++;
}
while (indexHigh > indexLow && numberList[indexHigh] > numberList[pivot]) {
indexHigh--;
}
if (indexLow < indexHigh) {
temp = numberList[indexLow];
numberList[indexLow] = numberList[indexHigh];
numberList[indexHigh] = temp;
}
}
assert(indexLow == indexHigh);
assert(indexLow > low);
if (numberList[indexLow] > numberList[pivot])
indexLow--;
assert(numberList[indexLow] <= numberList[pivot]);
temp = numberList[pivot];
numberList[pivot] = numberList[indexLow];
numberList[indexLow] = temp;
quickSort(numberList, low, indexLow-1);
quickSort(numberList, indexLow+1, high);
}
}
请注意,此实现比平时复杂得多。像这样在阵列中前后移动并不会真正获得太多收益。传统的实现代码更简单,更容易阅读和理解:
void quicksort_simpler(vector<long> &numberList, long low, long high) {
if (low >= high)
return;
long pivot = low;
long last = pivot;
long i;
for (i = pivot+1; i <= high; i++) {
if (numberList[i] <= numberList[pivot]) {
last++;
swap(numberList[last], numberList[i]);
}
}
swap(numberList[last], numberList[pivot]);
quicksort_simpler(numberList, low, last-1);
quicksort_simpler(numberList, last+1, high);
}
确保包含<algorithm> 以获取swap() 的声明。