冒泡排序(稳定排序,O(n^2)):比较相邻的两个数,最后使数据由小至大排序。
class BubbleSort{
public static void main(String [] args)
{
int[] a={23,54,21,53,16,49,26,30,18};
System.out.print("排序前:");
for(int i=0;i<a.length-1;i++){
System.out.print(" "+a[i]);
}
System.out.println(" ");
BubbleSort(a);
System.out.print("排序后:");
for(int i=0;i<a.length-1;i++){
System.out.print(" "+a[i]);
}
}
public static void BubbleSort(int[] a){
int temp=0;
for(int i=a.length-1;i>0;i--){
for(int j=0;j<i;j++){
if(a[j]>a[j+1]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
}
程序输出结果:
排序前: 23 54 21 53 16 49 26 30
排序后: 16 18 21 23 26 30 49 53