정렬

2016-08-02 5 views
1
이 getNumSwaps() 메소드는 인스턴스의 변수 값 numberOfSwaps 메소드가 호출되는 주요 기능에

그러나 그 열매를 맺지정렬

public class Solution { 
public int numberOfSwaps; 
Solution(){} 
    public int[] bubbleSort(int[] x){ // To sort the array 
    for (int i = 0; i < x.length; i++) { 
     for (int j = 0; j < x.length - 1; j++) { 
      if (x[j] > x[j + 1]) { 
       int tmp = x[j]; 
       x[j] = x[j + 1]; 
       x[j + 1] = tmp; 
       this.numberOfSwaps++;//This counts the number of Swaps 
      } 
     } 
     if (numberOfSwaps == 0) { 
     break; 
     } 
    } 
    return x; 
} 
public int getNumOfSwaps(){ //this method returns zero. ?? 
    return this.numberOfSwaps; 
} 

public static void main(String[] args) { 
     Scanner sc=new Scanner(System.in); 
     int arrLength=sc.nextInt();int i=0; 
      int [] myArry=new int[arrLength]; 
      Solution sln=new Solution(); 
      while(i<arrLength){ 
      myArry[i]=sc.nextInt(); 
      i++; 
     } 
     System.out.println("Array is sorted in "+sln.getNumOfSwaps()+" swaps."); 
     System.out.println("First Element: "+sln.bubbleSort(myArry)[0]+ 
         "\nLast Element: "+sln.bubbleSort(myArry)[arrLength-1]); 
} 
} 

답변

3
을 반환하지 않는 이유는 거품에 스왑의 수를 반환하려면

을 호출하기 전에 배열을 실제로 정렬하면 기본값 0이 나옵니다. 나는 또한 거품의 구현 일종의 올바른 것이 가정입니다

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    int arrLength = sc.nextInt(); 
    int i = 0; 
    int[] myArry = new int[arrLength]; 
    Solution sln = new Solution(); 
    while (i < arrLength) { 
     myArry[i] = sc.nextInt(); 
     i++; 
    } 

    // first sort the array, populating the number of swaps counter 
    int[] myArrySorted = sln.bubbleSort(myArry); 

    // then access the number of swaps counter 
    System.out.println("Array is sorted in " + sln.getNumOfSwaps() + " swaps."); 
    System.out.println("First Element: " + myArrySorted[0] + 
         "\nLast Element: " + myArrySorted[arrLength-1]); 
} 

: 귀하의 main() 방법은 다음과 같이 될 것이다. 어쨌든 내 대답은 당신이 어떤 가치 대신 제로가 된 이유를 설명해야합니다.

+1

@Op 그리고 다음 질문에 답하십시오. 두 번 이상 호출하려는 경우 정렬 기능의 시작 부분에서 카운터를 재설정해야합니다. – ABuckau

+0

@ABuckau 스왑의 개수가 처음에는 영구 변수가되어야한다고 생각하지 않습니다. 게다가이 알고리즘은 꺼져있을 수는 없지만 직접 체크하지는 않았습니다. –

+0

대 Op가 실제로 게시 된 것일까? 편집 : 배열이 참조에 의해 전달되었으므로 반환 값은 약간 이상합니다. 무의미하지만 신택스 설탕을 제공합니다. 초보자를 혼란스럽게하는 것은 아닙니다. – ABuckau