数据结构实验之查找四:二分查找
Time Limit: 30MS
Memory Limit: 65536KB
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<stdio.h>
#define N 1000010
int a[N], key;
int find(int a[], int l, int r)
{
int t = (r + l) / 2;
if(l > r)return -1;
if(key == a[t])return t;
else if(key > a[t])return find(a, t + 1, r);
else if(key < a[t])return find(a, l, t - 1);
}
int main()
{
int n, m, i;
scanf("%d%d", &n, &m);
for(i = 0; i <= n - 1; i++)
{
scanf("%d", &a[i]);
}
while(m--)
{
scanf("%d", &key);
printf("%d\n", find(a, 0, n - 1));
}
return 0;
}
#include<stdio.h>
#define N 1000010
int a[N], key;
int find(int a[], int l, int r)
{
int t = (r + l) / 2;
if(l > r)return -1;
if(key == a[t])return t;
else if(key > a[t])return find(a, t + 1, r);
else if(key < a[t])return find(a, l, t - 1);
}
int main()
{
int n, m, i;
scanf("%d%d", &n, &m);
for(i = 0; i <= n - 1; i++)
{
scanf("%d", &a[i]);
}
while(m--)
{
scanf("%d", &key);
printf("%d\n", find(a, 0, n - 1));
}
return 0;
}