杨嘉琪


私信TA

用户名:dotcpp0664564

访问量:1059

签 名:

等  级
排  名 633
经  验 3981
参赛次数 1
文章发表 21
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

TA的其他文章

1755: 姓名排序
浏览:9

解题思路:
折半/二分查找,必须采用顺序存储。

在有序的数组中,取中间值作为比较对象,若给定值与中间记录的关键字相等,则查找成功;

若给定值小于中间值记录的关键字,则在中间记录的左半区继续查找;

若给定值大于中间记录的关键字,则在中间记录的右半区查找。

注意事项:


#include<stdio.h>

#include<math.h>

int n,a[100001];/*n,与n个数的数组 */

int m,b; 

int main()

{

int i,j;

scanf("%d",&n);//输入n

for(i=1;i<=n;i++){

scanf("%d",&a[i]);

}

scanf("%d",&m);//输入m

//使用循环遍历,如果查找的数小于a数组中最小的数,或者大于最大的数,直接输出。

for(i=1;i<=m;i++){

scanf("%d",&b);//输入查找的数

if(a[1]>b){

printf("%d\n",a[1]);

continue;

}

if(a[n]<b){

printf("%d\n",a[n]);

continue;

}

//二分/折半查找

int low=1,high=n;

/*最低下标记录首位,最高下标记录末位*/

int mid;

while(low<=high){

mid=(low+high)/2;    /*折半*/ 

if(a[mid]>b) {    /*如果中间的数大于查找的数 */

high=mid-1;    /*最高位下标等于中间下标 -1*/

}else{     /*如果中间的数小于查找的数 */

low=mid+1;    /*最低下标等于中间下标+1 */

}

if(a[low]==b){

printf("%d\n",a[low]);

continue;

if(a[low]-b<b-a[low-1]){

printf("%d\n",a[low]);

continue;

}else{

printf("%d\n",a[low-1]);

continue;

}

}

////for循环结束


}


 

0.0分

0 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区