简书 賈小強
转载请注明原创出处,谢谢!
package com.lab1.test2;
public class Bubble {
public static void main(String[] args) {
Comparable[] a = { 5, 3, 1, 2, 4 };
sort(a);
show(a);
}
private static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
private static void sort(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 1; j < a.length - i; j++) {
if (less(a, j, j - 1)) {
exch(a, j - 1, j);
}
}
}
}
private static void exch(Comparable[] a, int i, int j) {
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
}
private static boolean less(Comparable[] a, int i, int j) {
return a[i].compareTo(a[j]) < 0;
}
}
输出
1 2 3 4 5
Happy learning !!