java 冒泡排序
************************
冒泡排序
算法描述:冒泡排序属于交换排序,以下沉冒泡由小到大为例
由前至后两两交换,将数组中的最大值交换到数组底部;
对剩余数组继续交换,将剩余数组中的最大值交换到剩余数组底部;
重复上述步骤,直至剩余数组长度为1,即全部交换完成
空间复杂度:冒泡排序需要一个额外辅助空间,o(1)
平均时间复杂度:o(n^2)
算法稳定性:想通大小的元素在排序前后位置保持不变,冒泡排序算法稳定
************************
示例
public class MyTest3 {
public static int[] generate(int length){
int[] a=new int[length];
for (int i=0;i<=length-1;i++){
a[i]=new Random().nextInt(1000);
}
return a;
}
public static void bubbleSort(int[] a){
int length=a.length;
boolean flag=true;
for (int i=1;i<length&&flag;i++){
flag=false;
for (int j=0;j<length-i;j++){
if (a[j]>a[j+1]){
flag=true;
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
public static void main(String[] args){
int[] a=generate(10);
System.out.println("排序前数组为:");
Arrays.stream(a).forEach(i -> System.out.print(i+" "));
bubbleSort(a);
System.out.println("\n\n排序后数组为:");
Arrays.stream(a).forEach(i -> System.out.print(i+" "));
}
}
控制台输出
排序前数组为:
88 203 295 118 793 788 311 983 790 4
排序后数组为:
4 88 118 203 295 311 788 790 793 983