C++算法(1) 排序 和 查找

sort排序

    #include<iostream>
    #include<string>
    #include<algorithm>

    using namespace std;

    void BubbleSort(int list[], int n);
    int main()
    {

        int list[5] = {1, 4, 2, 3};
        BubbleSort(list, 5);
        return 0;
    }
    void BubbleSort(int list[], int n)
    {
        for(int i = 0; i < n; i++)
        {
            sort(list, list + n, greater<int>()); //less<int>()
            cout << list[4 - i] << endl;
        }
    }

选择排序:

    #include<iostream>
    #include<string>
    #include<algorithm>

    using namespace std;

    void SelectSort(int* list, int n);
    int main()
    {

        int list[6] = {11, 4, 2, 13, 7};
        SelectSort(list, 6);
        return 0;
    }
    void SelectSort(int* list, int n)
    {
        for(int i = 0; i < n; i++)
        {
            for(int j = i + 1; j < n - 1; j++)
            {
                if(list[i] < list[j])
                    swap(list[i], list[j]);
                    else continue;

            }
            cout << list[i] << endl;
        }
    }

折半查找(二分查找)

前提:数据提前排序

    #include<iostream>
    #include<string>
    #include<algorithm>

    using namespace std;

    int BinarySort(int* list, int n, int num);
    int main()
    {

        int list[6] = {1, 4, 12, 13, 17};
        int n = BinarySort(list, 6, 12);
        cout << n;
        return 0;
    }
    int BinarySort(int* list, int n, int num)
    {
        int low, mid, high;
        low = 0, high = n - 1;
        while(low <= high)
        {
            mid = (low + high)/2;
            if(list[mid] == num)
                return mid;
            else if(list[mid] < num)
                low = mid + 1;
            else
                high = mid - 1;
        }
        return 0;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值