环境:Notpad ++ 6.0 + JDK 6.0.24
选择法排序的基本思想是首先从待排序的n个数中找出最小的一个与array[0]对换;再将array [1]到array [n]中的最小数与array [1]对换,依此类推。每比较一轮,找出待排序数中最小的一个数进行交换,共进行n-1次交换便可完成排序。选择法排序每执行一次外循环只进行一次数组元素的交换,可使交换的次数大大减少。
下图演示这一过程:
代码实现:
public class SelectSort{
public static void main(String [] args){
int a[] = {1, 2, 3, 56, 45, 22, 22, 26, 89, 99, 100};
System.out.println("排序前:");
for (int i = 0; i < a.length; ++ i){
System.out.print(a[i] + " ");
}
selectSort(a);
System.out.println("\n");
System.out.println("排序后:");
for (int i = 0; i < a.length; ++ i){
System.out.print(a[i] + " ");
}
}
public static void selectSort(int a[]){
int min = 0;
int temp = 0;
for (int i = 0; i < a.length - 1; ++ i){
min = i;
for (int j = i + 1; j < a.length; ++ j){
if (a[min] > a[j]){
min = j;
}
}
if (min != i){
temp = a[min];
a[min] = a[i];
a[i] = temp;
}
}
}
}
执行效果如图: