2013-03-12 78 views
0

我试图找出一个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); 
} 
+0

@icepack为什么会这样呢?这正是调试器是你最好的朋友的情况。 – 2013-03-12 07:57:37

+2

@icepack:bash.d是对的。 OP要求我们调试他的代码。他应该自己做。 – 2013-03-12 07:59:51

+0

@icepack:重新评估你的衰变,你错了。这里的论点是通过引用传递的。实施非常规且不安全,但适用于此用途。 – 2013-03-12 08:00:26

回答

1

就减少一个从pivot再次调用QuickSort前:

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 ......

+1

http://liveworkspace.org/code/4BlEkW$7证明这个答案是正确的 – 2013-03-12 08:12:49

+0

绝对不是一切 - 请参阅@ WhozCraig在问题 – SomeWittyUsername 2013-03-12 08:14:38

+0

下的评论@icepack:我想他删除了他的评论。无论如何,没问题,提问者写的逻辑奇怪,但它工作正常。在第一个'first = i-1'处,但是然后'i'会增加('i ++'),否则将使用'i + 1'。 – deepmax 2013-03-12 08:37:58

相关问题