1,原理:比较两个相邻的数,值大的向后移动;
2,N个数字要排序完成,总共进行N-1趟排序,每i趟的排序次数为(N-i)次,所以可以用双重循环实现
3,空间复杂度(O(1)) 时间复杂度(O(n^2)) 稳定性->稳定
4,冒泡排序及其优化:
public class Test25 {
//冒泡排序:
public static void bubbleSort(int array[]){
if (array == null || array.length ==0) return;
for (int i = 0; i < array.length-1; i++) {
for (int j = 0; j < array.length-i-1; j++) {
if (array[j] > array[j+1]){
int tmp = array[j];
array[j] = array[j+1];
array[j+1] = tmp;
}
}
}
}
//优化
public static void optimizedbubbleSort(int array[]){
if (array == null || array.length ==0) return;
boolean neednextsort = true;
for (int i = 0; i < array.length-1 && neednextsort; i++) {
neednextsort = false;
for (int j = 0; j < array.length - i - 1; j++) {
if (array[j]>array[j+1]){
int tmp = array[j];
array[j] = array[j+1];
array[j+1] = tmp;
neednextsort = true;
}
}
}
}
public static void main(String[] args) {
//冒泡排序
System.out.println("冒泡排序:");
int[] array = {6,3,7,5,2};
bubbleSort(array);
System.out.println(Arrays.toString(array));
//优化:
int[] array1 = {6,3,7,5,2};
optimizedbubbleSort(array1);
System.out.println(Arrays.toString(array1));
}
来源:CSDN
作者:SunStaday
链接:https://blog.csdn.net/SunStaday/article/details/104447235