[英]why the function only use the first element of array? (c++)
我试图找出一种QuickSort算法。 但是,看来我无法将数组传递给Partition和QuickSort函数。 它们仅处理数组的第一个元素。
我该如何解决?
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);
}
在再次调用QuickSort
之前,先从pivot
减少一个:
void QuickSort(int a[], int first, int last)
{
int pivot;
if (first < last)
{
pivot = Partition(a, first, last);
QuickSort(a, first, pivot - 1); // <-- HERE
QuickSort(a, pivot + 1, last);
}
}
一切都很好。 还要测试各种尺寸的a
:1,2,3,4,5,...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.