1、冒泡排序(Bubble Sort)
基本思想:两个数比较大小,较大的数下沉,较小的数冒起来。
算法描述:
1.比较相邻的元素。如果第一个比第二个大,就交换它们两个;
2.对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对,这样在最后的元素应该会是最大的数;
3.针对所有的元素重复以上的步骤,除了最后一个;
重复步骤1~3,直到排序完成。
public class BubbleSort {
public static void main(String[] args) {
int a[]={4,3,5,2,1};
/*
3 4 2 1 5
3 2 1 4 5
2 1 3 4 5
1 2 3 4 5
*/
for (int i = 0; i < a.length-1; i++) {
for (int j = 0; j < a.length-i-1; j++) {
int temp=0;
if (a[j]>a[j+1]){
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
System.out.println(Arrays.toString(a));
}
}
}