冒泡排序思想
算法描述
第二趟将第二大的数移动至倒数第二位
......
因此需要n-1趟;
/**
* @ClassName: BubbleSortMain
* @Author: Ming
* @Date: 2021/3/4 下午5:27
* @Description: 冒泡排序
*/
import com.jiajia.ArrayUtil.*; // 按包名导入
public class BubbleSortMain {
public static void main(String[] args) {
int[] arr = {2,5,1,3,8,5,7,4,3};
bubbleSort(arr);
ArrayUtil.print(arr);
}
/**
* 冒泡排序
* @param arr
*/
private static void bubbleSort(int[] arr) {
if(arr==null || arr.length < 2 ){
return;
}
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i -1; j++) { // 这里说明为什么需要-1
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
原文:https://www.cnblogs.com/sponges/p/14485486.html