(1)基本思想:在要排序的一组数中,对当前还未排好序的范围内的全部数,自上而下对相邻的两个数依次进行比较和调整,让较大的数往下沉,较小的往上冒。即:每当两相邻的数比较后发现它们的排序与排序要求相反时,就将它们互换。
/**
-
冒泡排序
-
Dec 14, 2016 9:09:14 AM
*/
public class BubbleSort {public static void main(String[] args) {
int a[] = {1,3,12,43,2,456,0}; System.out.println("从大到小,排序"); for (int i = 0; i < a.length; i++) { int c = 0; for (int j = 0; j < a.length; j++) { if(a[i] > a[j]){ c = a[i]; a[i] = a[j]; a[j] = c; } } } for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } System.out.println("从小到大"); for (int i = 0; i < a.length; i++) { int z = 0; for (int j = 0; j < a.length; j++) { if(a[i] < a[j]){ z = a[i]; a[i] = a[j]; a[j] = z; } } } for (int i = 0; i < a.length; i++) { System.out.println(a[i]); }
}
}