思路:其实没啥好说的,冒泡就是假定第一个是最小的,然后和后面的做比较,如果发现后面的数比较小,就交换一下;
改良:特定的时候,会出现已经排序好了,但我们的程序还没有跑完,这时候我们就定义一个flag,来检查是否有进行交换这个动作,如果没有,就说明已经排完了,这时候我们就可以结束循环了。
public class BubbleSort{
public static void main(String[] arge){
int[] arr = {1,8,5,4,6,77,12,56};
BubbleSort.bubbleSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void bubbleSort(int[] arr){
int temp = 0;
boolean flag = false;
for(int i = 0; i < arr.length ;i++ ){
for(int j = 0;j < arr.length - i -1; j++ ){
if(arr[j] > arr[j + 1]){
flag = true;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
if(!flag){
break;
}else{
flag = false;
}
}
}
}
//输出结果[1, 4, 5, 6, 8, 12, 56, 77]
以上内容仅供个人学习使用