2016-10-03 2 views
-5

나는 자바와 연습에서 빠른 정렬을 구현하려고하지만 어떤 이유로이 코드는 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

이것이 맞는 경우 대답을 수락하는 것을 고려하십시오. –

관련 문제