1. 程式人生 > >資料結構實驗之查詢四:二分查詢__Find

資料結構實驗之查詢四:二分查詢__Find

Time Limit: 30 ms Memory Limit: 65536 KiB

Problem Description
在一個給定的無重複元素的遞增序列裡,查詢與給定關鍵字相同的元素,若存在則輸出找到的位置,不存在輸出-1。

Input
一組輸入資料,輸入資料第一行首先輸入兩個正整數n ( n < = 10^6 )和m ( m < = 10^4 ),n是陣列中資料元素個數,隨後連續輸入n個正整數,輸入的資料保證數列遞增。
隨後m行輸入m個待查詢的關鍵字key

Output
若在給定的序列中能夠找到與關鍵字key相等的元素,則輸出位序(序號從0開始),否則輸出-1。

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

Sample Output
1
2
-1

AC程式碼:

#include<stdio.h>
int a[1000001],key;
int Find(int a[],int l,int r,int key)
{
    int x=(l+r)/2;
    if(l<=r)
    {
        if(key==a[x]) return x;
        else if(key<a[x]) Find(a,l,x-1,key);
        else Find(a,x+1,r,key);
    }
    else return -1;
}
int main()
{
    int n,m;
    while(~scanf("%d %d",&n,&m))
    {
        for(int i=0; i<n; i++)
        {
            scanf("%d",&a[i]);
        }
        while(m--)
        {
            scanf("%d",&key);
            printf("%d\n",Find(a,0,n-1,key));
        }
    }
    return 0;
}

————
餘生還請多多指教!