概要
选择排序(Selection Sort)是一种最简单直观的排序算法。它逻辑上将需要排序的元素分为两个序列,未排序的序列和已排序的序列,最初所有元素都在未排序的序列中,已排序的序列为空,通过重复的遍历未排序的序列,每次从未排序的序列中选择一个最小的元素放至已排序序列的末尾,直至未排序的序列为空。时间复杂度为O()。
Java实现代码
定义了一个排序接口,后面可用其他算法实现。
public interface Sort {
void sort(int[] array);
default void exchange(int[] array, int i, int j){
int item = array[i];
array[i] = array[j];
array[j] = item;
}
}
选择排序的实现类
/**
* 选择排序
*/
public class SelectionSort implements Sort{
@Override
public void sort(int[] array) {
int lo = 0,hi = array.length,min;
while(lo < hi){
min = lo;
for(int i=lo; i<hi-1; i++){
if(array[min] > array[i+1]){
min = i+1;
}
}
exchange(array,min,lo);
lo++;
}
}
public static void main(String[] args) {
SelectionSort selection = new SelectionSort();
TestUtil.test(10000,selection);
}
}
测试工具类,可生成测试数据和执行排序算法
public class TestUtil {
/**
* 返回一个大小为n的,由1到n之间的随机整数组成的数组
*/
public static int[] getRandomArray(int n){
return new Random().ints(n,1,n).toArray();
}
public void show(int array[]){
System.out.println(Arrays.toString(array));
}
public static void test(int n,Sort sort) {
int [] array = getRandomArray(n);
//show(array);
long startTime = System.currentTimeMillis();
sort.sort(array);
long endTime = System.currentTimeMillis();
//show(array);
System.out.println("程序运行时间:" + (endTime - startTime) + "ms");
}
}
性能测试
分别测试了10^3,10^4,10^5,10^6数量级的排序时间
10^3:程序运行时间:3ms
10^4:程序运行时间:39ms
10^5:程序运行时间:1592ms10^6:程序运行时间:164179ms
应用场景
选择排序的时间复杂度较高,一般只用于数据量较小的排序。由于它的元素交换次数比较少,效率会比冒泡排序好很多。