查找(二分查找、顺序查找)
程序员文章站
2022-03-13 23:07:32
...
1.针对数组a[8]={-32, 12, 16, 24, 36, 45, 59, 98},键盘输入一个数实现二分查找。两种方法实现:
(1)所有代码在一个main函数中;
#include<stdio.h>
void main()
{
int a[8] = { -32, 12, 16, 24, 36, 45, 59, 98 },s, low = 0, high = 7, mid,flag=0;
scanf("%d", &s);
while(low<=high) {
mid = (low + high) / 2;
if (s > a[mid])
low = mid + 1;
if (s < a[mid])
high = mid - 1;
if (s == a[mid]) {
flag = 1;
break;
}
}
if (flag == 1)
printf("找到");
else
printf("未找到");
}
(2)一维数组作为函数参数,利用函数调用实现
#include<stdio.h>
int fun(int a[],int s)
{
int low = 0, high = 7, mid, flag = 0;
while (low <= high) {
mid = (low + high) / 2;
if (s > a[mid])
low = mid + 1;
if (s < a[mid])
high = mid - 1;
if (s == a[mid]) {
return flag = 1;
break;
}
}
}
void main()
{
int a[8] = { -32, 12, 16, 24, 36, 45, 59, 98 },s,flag=0;
scanf("%d", &s);
flag = fun(a, s);
if (flag == 1)
printf("找到");
else
printf("未找到");
}
2.针对数组a[8] = {32,12,56,78,76,45,43,98},键盘输入一个数实现顺序查找。两种方法实现:
(1)所有代码在一个main函数中;
#include<stdio.h>
void main()
{
int a[8] = { 32,12,56,78,76,45,43,98 },s,i;
scanf("%d", &s);
for (i = 0; i < 8; ++i) {
if (a[i] == s) {
printf("找到");
break;
}
}
if (i == 8) //在for循环外
printf("未找到");
}
(2)一维数组作为函数参数,利用函数调用实现
#include<stdio.h>
int fun(int a[], int s)
{
int i;
for (i = 0; i < 8; ++i) {
if (a[i] == s) {
return 1;
break;
}
}
if (i == 8)
return 0;
}
void main()
{
int a[8] = { 32,12,56,78,76,45,43,98 },s,i,flag;
scanf("%d", &s);
flag = fun(a, s);
if(flag==1)
printf("找到");
else
printf("未找到");
}