以上文字均来自维基百科(国内需翻墙)。
用我自己的话来总结就是,每次选出一个最大的数放在末尾,如上图所示。
时间复杂度:O(n^2)
最优时间复杂度:O(n)
本人代码实现(JAVA):
public class BubbleSort {
public static void main(String[] args){
int []elem={3,4,12,6,87,1,22,45,5};
BubbleSort bSort=new BubbleSort();
bSort.sort(elem);
for(int i=0;i<elem.length;i++)
System.out.print(elem[i]+" ");
}
public int[] sort(int[] elem){
for(int i=0;i<elem.length-1;i++){
for(int j=0;j<elem.length-1-i;j++){
if(elem[j]>elem[j+1]){//每次选择出一个最大的放在末尾
int temp=elem[j];
elem[j]=elem[j+1];
elem[j+1]=temp;
}
}
}
return elem;
}
}