2016-10-03 49 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

如果是这样,请考虑接受答案。 –