排序-选择排序

算法思想

  • 对于一个序列num中的元素num[0]~num[n-1],令i从0到n-1枚举,进行n趟操作。
  • 每趟从待排序部分[i,n-1]中选择最小的元素,令其与待排序部分的第一个元素num[i]进行交换。这样元素num[i]就会与当前有序区间[0,i-1]形成新的有序区间[0,i]。
  • 于是在n趟操作后,所有的元素就会是有序的。[1]

代码实现

C++

#include <iostream>
#include <vector>
#include <algorithm>
#include <cassert>
using namespace std;
void select_sort(vector<int> &num)
{
    for (auto i = 0; i < num.size(); ++i)
    {
        // 有序区间[0,i-1] 无序区间[i,num.size()-1]
        int min_idx = i; // 无序区间中最小元素的下标
        for (auto j = i; j < num.size(); ++j)
        {
            if (num[j] < num[min_idx])
            {
                min_idx = j;
            }
        }

        // 最小元素与num[i]交换 使有序区间扩充为[0,i]
        int tmp = num[i];
        num[i] = num[min_idx];
        num[min_idx] = tmp;
    }
}
int main(int argc, char const *argv[])
{
    ios::sync_with_stdio(false);

    // 测试算法
    vector<int> a, a_copy;
    vector<int> b, b_copy;
    b = b_copy = {1, 2, 4, 0, 8, 7};
    vector<int> c, c_copy;
    c = c_copy = {9, 9, 9, 8, 8, 3, 1, 3};

    select_sort(a), sort(a_copy.begin(), a_copy.end());
    select_sort(b), sort(b_copy.begin(), b_copy.end());
    select_sort(c), sort(c_copy.begin(), c_copy.end());

    cout << (a == a_copy) << endl;
    cout << (b == b_copy) << endl;
    cout << (c == c_copy) << endl;

    assert(a == a_copy);
    assert(b == b_copy);
    assert(c == c_copy);

    return 0;
}

参考文献

[1] 《算法笔记》 胡凡 曾磊

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值