选择排序和冒泡法都是用来将数组元素按一定顺序排列的方法。
public class selection {
public static void sort(Comparable[] a){
//一共要选择a.length-1次
for (int i = 0; i < a.length-1; i++) {
Integer min = i;
for (int j = i; j < a.length; j++) {
if(greater(a[min],a[j])){
min = j;
}
}
exch(a,min,i);
}
}
public static boolean greater(Comparable a,Comparable b){
return a.compareTo(b)>0;
}
public static void exch(Comparable[] a,int i,int j){
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
import java.lang.reflect.Array;
import java.util.Arrays;
public class test{
public static void main(String[] args) {
Integer[] arr = {5,4,3,2,1};
selection.sort(arr);
System.out.println(Arrays.toString(arr));
}
}