2013-03-22 25 views
0

我花了很多時間試圖找出我沒有的權利;調試和所有,但我似乎無法把我的手指,爲什麼我的快速排序錯過了一些排序項目。快速排序除了幾個項目之外

我已經將我的代碼複製到下面的排序和分區。我有一種感覺,這是我看過的非常明顯的東西,但我花了無數時間來調試,研究和重寫我的代碼,結果總是如此。

// quicksort the subarray from a[lo] to a[hi] 
private void sort(Comparable[] a, int lo, int hi) { 
    if((hi-lo)>1){ 
     int pivot = partition(a,lo,hi); 
     sort(a,lo,pivot); 
     sort(a,pivot+1,hi); 
    } 
} 

// partition the subarray a[lo .. hi] by returning an index j 
// so that a[lo .. j-1] <= a[j] <= a[j+1 .. hi] 
private int partition(Comparable[] a, int lo, int hi) { 
    //find middle 
    int pivotIndex = (hi+lo)/2; 
    //pick pivot 
    Comparable pivot = a[pivotIndex]; 
    //create left and right pointers 
    int left = lo, right = hi; 
    //start comparing 
    //compare until left passes right 
    while(left<right){ 
     //while left is less than pivot move on 
     while(a[left].compareTo(pivot) < 0) left++; 
     //while right is greater than pivot move on 
     while(a[right].compareTo(pivot) > 0) right--; 
     //if the pointers have passed each other we're done 
     //if a[left] is greater than a[right] swap them 
     if(a[left].compareTo(a[right]) > 0){ 
      Comparable holder = a[left]; 
      a[left] = a[right]; 
      a[right] = holder; 
      //increment/decrement 
      left++; right--; 
     } 
    } 
    return right; 
} 
+0

是javascript嗎? :p – 2013-03-22 23:24:00

+0

@GrzegorzKaczan很確定它不是。重新簽署到Java。 – 2013-03-22 23:29:36

回答

0

只要刪除left++; right--;,一切都應該沒問題。

+0

我還沒有發現自己的錯誤,但我運行了一個測試用例,對'Character'[] s = {'z','y','x','a','b','c',' w','v','u'};'並刪除'left ++;正確 - ;'沒有糾正這個問題。 – Simon 2013-03-23 00:50:56

+0

很奇怪..我再次想到了一點,我猜想有關遞歸調用的問題出錯了。但我無法直接看到故障。 只需看看http://www.vogella.com/articles/JavaAlgorithmsQuicksort/article.html(與您的實現非常相似)的實現,但是在分區部分內或多或少地執行遞歸。 – fish 2013-03-23 12:23:34