2016-08-02 8 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

実際に投稿されたオペレーションとの対比*編集:配列は参照渡しされているので、戻り値はちょっと変わっていますが、無意味ですが構文上の砂糖を提供します。 – ABuckau