package algorithm.sort;
public class Bubble {
public static void sort(Comparable[] a){
for (int i = a.length-1 ; i > 0 ; i --){
for (int j = 0 ; j < i ; j ++){
if (!greater(a[i],a[j])){
exchange(a,i,j);
}
}
}
}
public static boolean greater(Comparable v,Comparable w){
return v.compareTo(w) > 0;
}
public static void exchange(Comparable[] a,int i,int j){
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
package algorithm.test;
import algorithm.sort.Bubble;
import java.util.Arrays;
public class BubbleTest {
public static void main(String[] args) {
Integer[] array = {5,3,4,1,2};
Bubble.sort(array);
System.out.println(Arrays.toString(array));
}
}
得到结果
[1, 2, 3, 4, 5]