2013-03-12 77 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

相關問題