直接上代码
public class BubbleSort {
public static void showArray(int[] array) {
for (int n = 0; n < array.length; n++) {
System.out.print(array[n]);
System.out.print(" ");
}
System.out.println();
}
public static int[] bubbleSortAsc(int[] before) {
int t;
for (int i = 0; i < before.length; i++) {
for (int j = 0; j < before.length - i - 1; j++) {
if (before[j] > before[j + 1]) {
t = before[j];
before[j] = before[j + 1];
before[j + 1] = t;
}
}
}
return before;
}
public static int[] bubbleSortDesc(int[] before) {
int t;
for (int i = 0; i < before.length; i++) {
for (int j = 0; j < before.length - i - 1; j++) {
if (before[j] < before[j + 1]) {
t = before[j];
before[j] = before[j + 1];
before[j + 1] = t;
}
}
}
return before;
}
public static void main(String[] args) {
int[] a = { 45, 66, 0, 32, 23, 23, 432, 3 };
System.out.println("未排序");
showArray(a);
int[] b = bubbleSortAsc(a);
System.out.println("正序:");
showArray(b);
int[] c = bubbleSortDesc(a);
System.out.println("倒序:");
showArray(c);
}
}