我试图找出一个QuickSort算法。 但是,看起来我无法将数组传递给Partition和QuickSort函数。它们只处理数组的第一个元素。为什么函数只使用数组的第一个元素? (C++)
我该如何解决?
template < class T > int getArrayLen(T & array) {
return (sizeof(array)/sizeof(array[0]));
}
int Partition(int a[], int first, int last) {
int pivot = a[last];
int i = first - 1;
for (int j = first; j < last; j++) {
if (a[j] <= pivot) {
i++;
swap(a[i], a[j]);
}
}
swap(a[i + 1], a[last]);
return i + 1;
}
void QuickSort(int a[], int first, int last) {
int pivot;
if (first < last) {
pivot = Partition(a, first, last);
QuickSort(a, first, pivot);
QuickSort(a, pivot + 1, last);
}
}
int main() {
int a[] = {
4, 32, 3, 13, 48, 45, 12, 54, 7, 42, 3, 12, 5, 24, 20
};
int length = getArrayLen(a);
QuickSort(a, 0, length - 1);
}
@icepack为什么会这样呢?这正是调试器是你最好的朋友的情况。 – 2013-03-12 07:57:37
@icepack:bash.d是对的。 OP要求我们调试他的代码。他应该自己做。 – 2013-03-12 07:59:51
@icepack:重新评估你的衰变,你错了。这里的论点是通过引用传递的。实施非常规且不安全,但适用于此用途。 – 2013-03-12 08:00:26