【发布时间】:2017-02-27 10:29:46
【问题描述】:
尝试使用指针创建快速排序算法,但运气不佳。我的代码可以编译但不起作用,我对如何纠正这个问题感到困惑。 任何帮助将不胜感激。
int* partition(int* start, int* stop) {
int* pivot = stop - 1; // you can randomly pick one as the pivot
int* i = start;
int* j = stop - 1;
for (;;) {
while (i < pivot && i < stop) ++i; // skip "low" on left side
while (j >= pivot && j > start) --j; // skip "high" on right side
if (*i >= *j) break;
swap(i, j); // swap out-of-place items
}
swap(*(stop - 1), *i); // swap pivot to the final place i
return i;
}
void quickSort(int* start, int* stop) {
if (stop - start <= 1) return;
int* pivot = partition(start, stop);
quickSort(start, pivot);
quickSort(pivot + 1, stop);
}
【问题讨论】:
-
怎么不工作了?你期待什么,你得到了什么?请描述要解决的问题。
-
该程序旨在输出算法的类型、数据集的大小和数据集的类型。它目前适用于其他排序函数,但这个函数不返回任何内容。
-
int* pivot = stop - 1;哪里定义了停止?你怎么能确定stop - 1是一个可用的地址,即你所有的排序值都是连续存储的? -
在
swap(i, j);中,您显然传递了指向函数的指针,而在swap(*(stop - 1), *i);中,您传递了int值。你认为哪一个是正确的......?
标签: c++ sorting pointers quicksort