zoukankan      html  css  js  c++  java
  • 初级算法

    两种算法一起使用

    冒泡算法的时间复杂度是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;
    }
  • 相关阅读:
    poj 2155 B
    hdu 1556 A
    hdu 1556 A
    #366 A-C
    最长上升子序列
    Codeforces Div3 #501 A-E(2) F以后补
    字典的建立 查找
    字典序大小
    头文件模板
    01背包模板 及 优化
  • 原文地址:https://www.cnblogs.com/strive-sun/p/14425551.html
Copyright © 2011-2022 走看看