C++ 选择排序

1、在冒泡的基础上减少了交换的次数,最多交换n-1次,代码如下:

// Example program
#include <iostream>
#include <string>
#include <algorithm>  //sort、swap
using namespace std;


void swap(int& a, int& b)
{
    int tmp = a;
    a = b;
    b = tmp;
}

int selectSort(int* arr/*int arr[]*/, int len)
{
    if(NULL == arr)
    {
        return -1;
    }

    for(int i = 0; i < len; i++)
    {
        int min = i;
        for(int j = i+1; j < len; j++)
        {
            if(arr[j] < arr[min])
            {
                min = j;
            }
        }
        
        if(min != i)
        {
            swap(arr[i],arr[min]);  /*标准库里也有这个*/
        }
    }
    
    return 0;
}

int main()
{
    int arr[] = {2,9,3,1,5,4};
    int length = sizeof(arr)/sizeof(int);
    int ret = 0;
    //cout << length << endl;
    
    ret = selectSort(arr,length);
    //sort(arr,arr+length);    /*调用标准库的算法*/
    if(ret != 0)
    {
        cout << "Fail to sort!\n";
    }

    for(auto elem : arr)
        cout << elem << ' ';
    cout << endl;
    
    return 0;
}

2、利用容器

// Example program
#include <iostream>
#include <vector>
//#include <algorithm>  //swap
using namespace std;

template<typename T>
void myswap(T& a, T& b)   /*自定义的myswap,不要和标准库内的同名*/
{
    T tmp = a;
    a = b;
    b = tmp;
}

int selectSort(vector<int>& v)
{
    int len = v.size();
    
    if(len == 0)
    {
        cout << "The vector is empty!\n";
        return -1;
    }

    for(int i = 0; i < len; ++i)
    {
        int min = i;
        for(int j = i+1; j < len; ++j)
        {
            if(v[j] < v[min])
            {
                min = j;
            }
        }
        
        if(min != i)
        {
            myswap(v[i],v[min]);
        }
    }
        
    return 0;    
}

int main()
{
    vector<int> vec{6,3,1,5,2};
    
    selectSort(vec);
    
    for(auto& elem : vec)
    {
        cout << elem << ' ';
    }
    return 0;
}

3、十大排序算法:https://www.cnblogs.com/onepixel/p/7674659.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值