2016-10-03 48 views
-5

我試圖在java中實現快速排序,但由於某種原因,這段代碼甚至沒有輸入while循環,並在註釋中標記爲下面,它並沒有真正對數組進行排序。這個遞歸快速排序程序爲什麼不起作用?

public class Solution2 { 
    private int[] ar; 
    Solution2(int [] ar) { 
     this.ar = ar; 
    } 
    public void quickSort(int left, int right) { 
     if ((right - left) <= 0) { 
      return; } 
     else { 
       int pivot = ar[right]; 
       int partition = partitionIt(right, left, pivot); 
       quickSort(left, partition-1); 
       quickSort(partition, right);} 
    } 

    public int partitionIt (int leftptr, int rightptr, int pivot) { 

     int left = leftptr-1; 
     int right = rightptr; 
     while (true) { 
      while (right > 0 && ar[--right] > pivot) // Code does not loop through to the small elemen 
       ; 
      while (ar[++left] < pivot) ; 
      if (left >= right) { 
       break; 
      } 
      else { 
       swap(left, right); 
      } 
      swap(left, rightptr); 
     } 
     return left; 
    } 

    public int[] swap (int dex1, int dex2) { 
     int temp = ar[dex1]; 
     ar[dex1] = ar[dex2]; 
     ar[dex2] = temp; 
     return ar; 
    } 



    public void printArray() { 
     for(int n: ar){ 
      System.out.print(n+" "); 
     } 
     System.out.println(""); 
    } 

} 

public class Immplementer { 

    public static void main(String[] args) { 
     Scanner in = new Scanner(System.in); 
     int n = in.nextInt(); 
     int[] ar = new int[n]; 
     for(int i=0;i<n;i++){ 
      ar[i]=in.nextInt(); 
     } 
     Solution2 soln = new Solution2(ar); 
     soln.printArray(); 
     soln.quickSort(0, ar.length -1); 
     soln.printArray(); 
    }  
} 

請注意,這不是一個關於如何排序的作品快速的問題,但這個關於此特定錯誤,我無法弄清楚。請幫助。

+5

您是否嘗試過使用調試器? –

+0

爲什麼在while循環打開的行尾有分號? – splay

+0

是的,我做過了,但我想到了我的錯字,並且我無法幫助我一直詛咒自己。 。 – CaRtY5532

回答

1

代碼工作正常,但有一個錯誤:

int partition = partitionIt(right, left, pivot); 

相反,它應該是:

int partition = partitionIt(left, right, pivot); 
+0

如果是這樣,請考慮接受答案。 –