数据结构实验之查找四:二分查找

Problem Description

在一个给定的无重复元素的递增序列里,查找与给定关键字相同的元素,若存在则输出找到的位置,不存在输出-1。

Input

一组输入数据,输入数据第一行首先输入两个正整数n ( n < = 10^6 )和m ( m < = 10^4 ),n是数组中数据元素个数,随后连续输入n个正整数,输入的数据保证数列递增。
随后m行输入m个待查找的关键字key

Output

若在给定的序列中能够找到与关键字key相等的元素,则输出位序(序号从0开始),否则输出-1。

Example Input

8 3
4 6 8 9 13 20 21 22
6
8
17

Example Output

1
2
-1

Hint

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int a[100005];
int binsearch(int left,int right,int key)
{
    while(left<=right)
    {
        int mid = (left+right)/2;
        if(a[mid] > key)
        {
            right = mid-1;
        }
        else if(a[mid] < key)
        {
            left = mid+1;
        }
        else
            return mid;
    }
    return -1;
}
int main()
{
    int n,m;
    cin>>n>>m;
    for(int i = 0; i < n; ++i)
    {
        scanf("%d",&a[i]);
    }
    while(m--)
    {
        int key;
        cin>>key;
        int pos = binsearch(0,n-1,key);
        cout<<pos<<endl;
    }
    return 0;
}



猜你喜欢

转载自blog.csdn.net/minose/article/details/78881758