两种for循环条件不一样,一种是冒泡一种是沉底,排序的思想都是两两比较;
注意看Bubble我注释的代码,自己Debug理解一下
package com.apesblog.sort.bubble;
public class Bubble {
//初始a[]={ 3, 2, 1 };
//i = 0;
//j = 2;a->312
//j = 1;a->132
//j = 0;结束循环;
//i = 1;
//j = 2;a->123
//j = 1;结束循环;
//i = 2;结束循环;
public static void sortUp(Comparable[] a) {
for (int i = 0; i < a.length - 1; i++) {
for (int j = a.length - 1; j > i; j--) {
if (greater(a[j - 1], a[j])) {
exch(a, j - 1, j);
}
}
}
}
//初始a[]={ 3, 2, 1 };
//i = 2;
//j = 0;a->231
//j = 1;a->213
//j = 2;结束循环;
//i = 1;
//j = 0;a->123
//j = 1;结束循环;
//i = 0;结束循环;
public static void sortDown(Comparable[] a) {
for (int i = a.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (greater(a[j], a[j + 1])) {
exch(a, j, j + 1);
}
}
}
}
private static boolean greater(Comparable i, Comparable j) {
return i.compareTo(j) > 0;
}
private static void exch(Comparable[] a, int i, int j) {
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
}
测试类如下:
package com.apesblog.sort.bubble;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
Integer[] a = { 3, 2, 1 };
Bubble.sortUp(a);
System.out.println("冒泡:" + Arrays.toString(a));
Integer[] aa = { 3, 2, 1 };
Bubble.sortDown(aa);
System.out.println("沉底:" + Arrays.toString(aa));
package com.apesblog.sort.bubble;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
Integer[] a = { 4, 5, 6, 3, 2, 1 };
Bubble.sortUp(a);
System.out.println("冒泡:" + Arrays.toString(a));
String[] s = { "d", "e", "f", "c", "b", "a" };
Bubble.sortUp(s);
System.out.println("冒泡:" + Arrays.toString(s));
Integer[] aa = { 4, 5, 6, 3, 2, 1 };
Bubble.sortDown(aa);
System.out.println("沉底:" + Arrays.toString(aa));
String[] ss = { "d", "e", "f", "c", "b", "a" };
Bubble.sortDown(ss);
System.out.println("沉底:" + Arrays.toString(ss));
}
}
评论区