java冒泡排序算法
冒泡排序(升序)
public class Test {
//冒泡排序(升序)
public static void main(String[] args) {
int a[]={9,3,1,8,6,7};
int tmp;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length-i-1; j++) {
if (a[j] > a[j+1]) {
tmp=a[j];
a[j]=a[j+1];
a[j+1]=tmp;
}
}
}
for (int b = 0; b <a.length ; b++) {
System.out.println(a[b]);
}
}
}
结果为
1
3
6
7
8
9
冒泡排序(降序)
public class Test {
//冒泡排序(降序)
public static void main(String[] args) {
int a[]={9,3,1,8,6,7};
int tmp;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length-i-1; j++) {
if (a[j] < a[j+1]) {
tmp=a[j];
a[j]=a[j+1];
a[j+1]=tmp;
}
}
}
for (int b = 0; b <a.length ; b++) {
System.out.println(a[b]);
}
}
}
结果为
9
8
7
6
3
1