M--二分查找

Time Limit: 600MS Memory Limit: 65536KB

Problem Description

给出含有n个数的升序序列,保证序列中的数两两不相等,这n个数编号从1 到n。
然后给出q次询问,每次询问给出一个数x,若x存在于此序列中,则输出其编号,否则输出-1。

Input

单组输入。首先输入一个整数n(1 <= n && n <= 3000000),接下的一行包含n个数。
再接下来的一行包含一个正整数q(1 <= q && q <= 10000),表示有q次询问。
再接下来的q行,每行包含一个正整数x。

Output

对于每次询问,输出一个整数代表答案。

Example Input

5
1 3 5 7 9
3
1
5
8

Example Output

1
3
-1
#include <stdio.h>
#include <stdlib.h>
int a[3000005], n;
int find(int x)//假定这是一个升序数组
{
    int i, j, mid, y;
    i = 0;
    j = n - 1;
    mid = (i+j)/2;
    while(i<=j)
    {
        if(a[mid] == x)
        {
            y = mid + 1;
            break;
        }
        else
        {
            if(a[mid] > x)
                j = mid - 1;
            else
                i = mid + 1;
        }
     mid = (i + j)/2;
    }
    if(i>j) y = -1;
    return y;    //数组中没有要查的数,返回-1;
}
int main()
{
    int q, x, i, y;
    scanf("%d", &n);
    for(i = 0; i < n; i++)
    {
        scanf("%d", &a[i]);
    }
    scanf("%d", &q);
    while(q--)
    {
        scanf("%d", &x);
        y = find(x);
        printf("%d\n", y);
    }
    return 0;
}
如果输入的数组是乱序的应该先使用快排