冒泡排序法就是通过对相邻元素的比较和交换,如果前一个元素大于后一个元素则进行交换这里以33, 21, 54, 55, 666, 345, 543, 2, 678为例,排序之后的数组为2 21 33 54 55 345 543 666 678
public class Test {
public static void main(String[] args) {
int a[] = { 33, 21, 54, 55, 666, 345, 543, 2, 678 };
int i, j ;
for (i = 0; i < a.length; i++) {
for (j = 0; j < a.length - i; j++) {
try {
if (a[j] > a[j + 1]) {
swap(a, j, j + 1);
}
} catch (Exception e) {
}
}
}
for (i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
public static void swap(int a[] , int i , int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}