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 스왑의 개수가 처음에는 영구 변수가되어야한다고 생각하지 않습니다. 게다가이 알고리즘은 꺼져있을 수는 없지만 직접 체크하지는 않았습니다. –
대 Op가 실제로 게시 된 것일까? 편집 : 배열이 참조에 의해 전달되었으므로 반환 값은 약간 이상합니다. 무의미하지만 신택스 설탕을 제공합니다. 초보자를 혼란스럽게하는 것은 아닙니다. – ABuckau