排序(四)选择排序:简单选择排序

简单选择排序

  首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。

  算法描述

  1. 从未排序序列中,找到关键字最小的元素
  2. 如果最小元素不是未排序序列的第一个元素,将其和未排序序列第一个元素互换
  3. 重复1、2步,直到排序结束。

  动图演示

  实例验证

  10000个数字组成的数组排序,耗时大概率在85ms-100ms。

public class TestSelectSort {

    public static void main(String[] args) {
        System.out.println("old:" + Arrays.asList(SelectData.array).toString().substring(0, 100) + "...");
        Long start = System.currentTimeMillis();
        sort(SelectData.array);
        Long end = System.currentTimeMillis();
        System.out.println("new:" + Arrays.asList(SelectData.array).toString().substring(0, 100) + "...");
        System.out.println("耗时:" + (end - start));
    }

    static void sort(Integer[] array) {
        for (int i = 0; i < array.length; i++) {
            int minIndex = i;
            for (int j = i + 1; j < array.length; j++) {
                if (array[j] < array[minIndex]) {
                    minIndex = j;
                }
            }
            if (minIndex != i) {
                int tmp = array[minIndex];
                array[minIndex] = array[i];
                array[i] = tmp;
            }
        }
    }
}

class SelectData {
    public static Integer[] array;
    static {
        array = new Integer[10000];
        for (Integer i = 0; i < 10000; i++) {
            Random r = new Random();
            array[i] = r.nextInt(100000);
        }
    }
}
View Code

  结果展示:

old:[55347, 40199, 3617, 29961, 80690, 39354, 27896, 69816, 97022, 50826, 35826, 82809, 50004, 21005, 80...
new:[0, 15, 23, 43, 57, 60, 69, 70, 74, 89, 95, 99, 99, 101, 117, 119, 137, 141, 151, 155, 177, 179, 184...
耗时:92 

  复杂度分析

平均时间复杂度最好情况最坏情况空间复杂度
O(n²) O(n²) O(n²) O(1)

  选择排序不稳定,比如5 8 5 2 9,第一次选择排序时,第一个5会与2交换,导致5的顺序变了

原文地址:https://www.cnblogs.com/ryjJava/p/14411842.html