题解 | #查找#二分查找#

查找

https://www.nowcoder.com/practice/d93db01c2ee44e8a9237d63842aca8aa

//二分查找方法实现
#include<iostream>
#include<algorithm>

const int MAX = 100;

class BinarySearch
{
    private:
    int m_low, m_high;
    int m_Index;
    public:
    BinarySearch(int low, int high, int index)
        : m_low(low), m_high(high), m_Index(index)
    {
    }

    bool Search(int* array)
    {
        int mid;
        while(m_low <= m_high)
        {
            mid = (m_low + m_high) / 2;
            if(array[mid] == m_Index)
            {
                return true;
            }else if(array[mid] > m_Index)
            {
                m_high = mid - 1;
            }else{
                m_low = mid + 1;
            }
        }
        return false;
    }
};

int main()
{
    int n;
    while (std::cin >> n)
    {
        int A[MAX];
        for(int i = 0;i < n;i++)
        {
            std::cin >> A[i];
        }
        std::sort(A, A+n);
        int m, b;
        std::cin >> m;
        for(int i = 0;i < m;i++)
        {
            std::cin >> b;
            BinarySearch binary(0, n-1, b);
            if(binary.Search(A))
            {
                std::cout << "YES" << std::endl;
            }else{
                std::cout << "NO" << std::endl;
            }
        }
        
    }
    
}

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务