Java选择排序

概要

        选择排序(Selection Sort)是一种最简单直观的排序算法。它逻辑上将需要排序的元素分为两个序列,未排序的序列和已排序的序列,最初所有元素都在未排序的序列中,已排序的序列为空,通过重复的遍历未排序的序列,每次从未排序的序列中选择一个最小的元素放至已排序序列的末尾,直至未排序的序列为空。时间复杂度为O(n^{2})。

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:程序运行时间:1592ms

10^6:程序运行时间:164179ms

应用场景 

        选择排序的时间复杂度较高,一般只用于数据量较小的排序。由于它的元素交换次数比较少,效率会比冒泡排序好很多。

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值