应该按顺序排列数组成员。任何人都可以在冒泡排序中逐步解释。
//bubble sorting technique to sort the integer in ascending order
int n = 5;
int limit = n- 1;//elements from 0 to n-1
boolean flag = false;//if it is true,swapping is done
int temp;// temporary variable
for(int i=0 ; i<limit; i++){
for(int j = 0;j<limit-i;j++){
//if first element is bigger than second one , then swap
if(arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;//true->swapping done
flag = true;
}
if(flag==false) break;//no swapping,so come out
else flag = false;//assign initial value
}
//display sorted array
system.out.println("the sorted array is")
for(int i=0;i<5;i++)
system.out.println(arr[i]);
}
输入:50 23 11 99 23
输出:11 23 23 50 99
答案 0 :(得分:0)
你的最后一个结束括号是错误的,所以你得到每个外循环周期的"the sorted array is"
输出。向上移动3行:
if (flag==false)
break;
else
flag = false;
}
} // Move it here
system.out.println("the sorted array is")
for(int i=0;i<5;i++)
system.out.println(arr[i]);