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]);
}
}
@Opを入力し、次の質問に答えるために:ソート関数の先頭に複数回コールする予定の場合は、カウンターをリセットする必要があります。 – ABuckau
@ABuckau私は、スワップの数が永続的な変数でなければならないとは思っていません。また、このアルゴリズム以外にも、私は決してそれをチェックしませんでした。 –
実際に投稿されたオペレーションとの対比*編集:配列は参照渡しされているので、戻り値はちょっと変わっていますが、無意味ですが構文上の砂糖を提供します。 – ABuckau