冒泡排序的思想就是:双层嵌套循环,记住要<=数组.lenght-1,不然会少比较一轮。比较大小交换
/**
* 冒泡排序,最简单的排序,就是双层循环
* @param a
*/
public void bubble(int[] a){
int i = 0,j = 0,temp;
for (i = 0;i <= a.length-1;i++){
for (j = i+1;j <= a.length-1;j++){ // i后面的循环
if (a[i] > a[j] ) {//比较大小交换
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
}
@Test
public void test_bubble(){
int[] a = {5,5,688,8,9,45,213,2,8,17,19};
for (int s:a) {
System.out.print(s+" ");
}
bubble(a);
System.out.println();
for (int s:a) {
System.out.print(s+" ");
}
}
网友评论