选择排序 Select Sort

选择排序

1. 基本原理

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

2. 算法步骤

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

3. 动画演示

以找最小元素为例:

在这里插入图片描述

4. 参考实现

import java.util.Arrays;

/**
 * @author wylu
 */
public class SelectSort {
    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    /**
     * 每一轮选择最大元素
     * @param arr 待排序数组
     */
    public static void maxSelectSort(int[] arr) {
        for (int i = arr.length - 1; i > 0; i--) {
            int maxIdx = i;
            for (int j = 0; j < i; j++) {
                if (arr[j] > arr[maxIdx]) {
                    maxIdx = j;
                }
            }
            swap(arr, maxIdx, i);
        }
    }

    /**
     * 每一轮选择最小元素
     * @param arr 待排序数组
     */
    public static void minSelectSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int minIdx = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[minIdx]) {
                    minIdx = j;
                }
            }
            swap(arr, minIdx, i);
        }
    }

    public static void main(String[] args) {
        int[] arr = {3, 1, 4, 9, 6, 0, 7, 2, 5, 8};
        SelectSort.maxSelectSort(arr);
        System.out.println(Arrays.toString(arr));

        int[] arr2 = {12, 8, 30, 25, -1, 0 , 17, 8, 10};
        SelectSort.minSelectSort(arr2);
        System.out.println(Arrays.toString(arr2));
    }
}

5. 复杂度分析

排序算法平均时间复杂度最好情况最坏情况空间复杂度排序方式稳定性
选择排序 O ( n 2 ) O(n^2) O(n2) O ( n 2 ) O(n^2) O(n2) O ( n 2 ) O(n^2) O(n2) O ( 1 ) O(1) O(1)In-place不稳定

6. References

图片来源
https://youliao.163yun.com/api-server/rss/xiaomi/item/IN2WDOMKAWVNTZV.html?ref=browser_news&s=mb&cp=cn-netease-youliao-browser&docid=44797c69e120935b2c4790d933d02a9b&itemtype=news&cateCode=rec&category=%E7%A7%91%E6%8A%80

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值