初级算法 - 冒泡排序和二分法

两种算法一起使用

冒泡算法的时间复杂度是n的平方,二分法是log(m+n)

#include <iostream>
#include <vector>
#include <string>

int main()
{
    std::vector<int> nums{ 20,10,324,43,415,2,45,68,9,100,98};
    int len = nums.size();
    int low = 0, high = 0, temp, mid;
    if (len % 2 != 0)
    {
        //奇数
        mid = (len - 1) / 2;
    }
    else
    {
        //偶数
        mid = len / 2 - 1;
    }
        
    int n;
    //冒泡排序
    for (int i = 0; i < len; i++)
    {
        for (int j = 0; j < len - i - 1; j++)
        {
            if (nums[j] > nums[j + 1])
            {
                temp = nums[j];
                nums[j] = nums[j + 1];
                nums[j + 1] = temp;
            }
        }
    }
    for (int k = 0; k < len; k++)
    {
        std::cout << nums[k] << " ";        
    }
    std::cout << std::endl;
    //二分法找到这个数的下标
    std::cin >> n;
    if (nums[0] == n)
    {
        std::cout << "下标: 0" << std::endl;
        return 0;
        
    }
    if (nums[len-1] == n)
    {
        std::cout << "下标: " <<len-1<< std::endl;
        return 0;
    }
    while (1)
    {
        if (n == nums[mid])
        {
            std::cout << "下标:" << mid << std::endl;
            break;
        }
        
        else if (n > nums[mid])
        {
            low = nums[mid + 1];
            if (low == n)
            {
                std::cout << "下标:" << mid + 1 << std::endl;
                break;
            }
            mid = (mid + len) / 2;
        }
        else
        {
            high = nums[mid - 1];
            mid = (mid + 0) / 2;
        }    

    }
    return 0;
}

 

posted @ 2021-02-21 13:22  strive-sun  阅读(153)  评论(0编辑  收藏  举报