[英]why the function only use the first element of array? (c++)
I was trying to figure out a QuickSort algorithm. 我试图找出一种QuickSort算法。 But, it looks like I can't pass the array into Partition and QuickSort function.
但是,看来我无法将数组传递给Partition和QuickSort函数。 They only process the first element of the array.
它们仅处理数组的第一个元素。
How can I fix it? 我该如何解决?
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);
}
Just decrease one from pivot
before calling QuickSort
again: 在再次调用
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);
}
}
And every thing is OK. 一切都很好。 Also test for various sizes of
a
: 1, 2, 3, 4, 5, ... 还要测试各种尺寸的
a
:1,2,3,4,5,...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.