排序算法之选择排序

选择排序(Selection Sort)

该算法的实现思想为:对于具有 n 个记录的无序表遍历 n-1 次,第 i 次从无序表中第 i 个记录开始,找出后序关键字中最小的记录,然后放置在第 i 的位置上。

算法描述

  • 初始状态:无序区为R[1...n];
  • 从第1个开始,minIndex为最小值的索引,初始值为1,R[minIndex]和其余n-1个数进行比较,当出现R[minIndex] > R[m]时,改变minIndex的值,当比较到最后一个的时候,进行值 R[minIndex]和R[1]的交换;
  • 重复流程2,一直到n-1

代码实现

public class SelectionSort {
    public static void main(String[] args) {
        int[] num = new int[]{5,3,2,6,4,7,1};
        num = sort(num);
        for (int k : num) {
            System.out.print(k + " ");
        }
    }
    public static int[] sort(int[] num){
        for (int i =0; i< num.length; i++){
            int minIndex = i;
            for (int j = i+1; j < num.length; j++) {
                if(num[minIndex] > num[j]){
                    minIndex = j;
                }
            }
            if(num[minIndex] != num[i]){
                int temp = num[minIndex];
                num[minIndex] = num[i];
                num[i] = temp;
            }
        }
        return num;
    }
}

算法分析

最佳情况:T(n) = O(n2) 最差情况:T(n) = O(n2) 平均情况:T(n) = O(n2)

参考:
https://www.cnblogs.com/guoyaohua/p/8600214.html
http://data.biancheng.net/view/70.html

posted @ 2019-12-05 17:37  cilieyes  阅读(129)  评论(0编辑  收藏  举报