首先看源码:
public class SelectSort {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SelectSort mSelectSort = new SelectSort();
Integer [] input = {1 , 6, 3, 2, 9};
System.out.println("原始顺序:");
mSelectSort.showArray(input);
mSelectSort.selectSort(input);
System.out.println("选择排序后:");
mSelectSort.showArray(input);
}
//选择法排序
public void selectSort(Comparable[] in){
int N = in.length;
for(int i=0; i<N; i++){
int min = i;
for(int j=i+1; j<N; j++){
if(isLess(in[j], in[min])){
min = j;
}
}
swap(in, min, i);
}
}
public boolean isLess(Comparable a, Comparable b){
if(a.compareTo(b) < 0){
return true;
}
else{
return false;
}
}
public void swap(Comparable[] in, int i, int j){
Comparable temp = in[i];
in[i] = in[j];
in[j] = temp;
}
public void showArray(Integer[] a){
for(Integer temp : a){
System.out.print(" " + temp);
}
System.out.println();
}
}
以上程序的注意点:因为在selectSort函数中输入参数为Comparable[]类型,所以输入数组是Integer而不是int,int是个基本变量,而Integer是个对象。
选择排序基本思想: 找出最小的,跟第一个交换,然后第一个就不参加排序了。从第二个开始再次扫描得到最小的,跟第二个交换,依次类推。
特点有二:
1、比较次数:无论初始数组是否有序,比较次数都是固定的。这里的比较次数也可以当成时间复杂度。
2、数据交换次数:跟数组的长度成正比关系,在上述代码的基础上可以进行改进,当J不等于min时,才进行交换。如果两者相当则不交换。