1. 冒泡排序
将数组【5,2,15,9,13,20,8】按从小到大的顺序排序。
因为需要遍历2次循环,对应的时间复杂度为O(n2)
2. 思路:
- 遍历相邻的2个数字,如果第一个数字大于第二个数字,则第一个数字和第二个数字调换位置。
- 优化点:如果从某两个位置开始,之后都没发生过位置调换,则不需要进行后面的大循环。
3. 代码
/**
* 冒泡排序: 从小到大排序
* 遍历相邻的2个数字,如果第一个数字大于第二个数字,则第一个数字和第二个数字调换位置。
* @Author: KingWang
* @Date: 2021/6/9
* @Desc:
**/
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5,2,15,9,13,20,8};
System.out.println("排序前:" + Arrays.toString(arr));
bubbleSort(arr);
System.out.println("排序后:" + Arrays.toString(arr));
}
//冒泡排序
private static void bubbleSort(int[] arr) {
int temp = 0;
boolean hasMove = false;
int cycleCount = 0;
for (int i = 0; i <arr.length ; i++) {
for (int j = 0; j <arr.length-1-i ; j++) {
//如果前面的大于后面的,交换位置
if(arr[j] > arr[j+1]){
temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
hasMove = true;
}
}
cycleCount++;
//优化:如果后面没有发生移动,那么可以直接退出大循环
if(!hasMove){
break;
}else{
hasMove = false;
}
}
System.out.println("遍历次数:" + cycleCount);
}
4.结果验证
当关闭下面一段优化代码时,多了2次无效次数的遍历:
//优化:如果后面没有发生移动,那么可以直接退出大循环
if(!hasMove){
break;
}else{
hasMove = false;
}