选择排序

Code

package kb.algorithm;

public class SelectionSort {
    public static void main(String[] args) {
        int[] a = new int[]{3, 6, 4, 7, 2};
        sort(a);
        StringBuilder sb = new StringBuilder(20);
        for (int i = 0; i < a.length; i++) {
            sb.append(a[i]);
            sb.append(",");
        }
        System.out.println(sb);
    }

    public static void sort(int[] a) {
        int minIndex = 0;
        int temp = 0;
        int len = a.length;
        for (int i = 0; i < len - 1; i++) {
            minIndex = i;
            for (int j = i + 1; j < len; j++) {
                if (a[j] < a[minIndex]) {
                    minIndex = j;
                }
            }
            temp = a[i];
            a[i] = a[minIndex];
            a[minIndex] = temp;
        }
    }
}

执行结果

2,3,4,6,7,

分析演示

img

每次找出一个最小的放到前面。

  1. 最好、平均,最坏O(n^2)。
  2. 非稳定排序。
posted @ 2021-05-18 23:22  xuan_wu  阅读(45)  评论(0编辑  收藏  举报