插值查找算法

本文介绍了一种插入式搜索算法的实现方式,并通过一个具体的示例展示了如何在有序数组中查找指定元素。该算法利用了数学计算来缩小搜索范围,提高了搜索效率。
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<math.h>
 4 #include<ctype.h>
 5 #include<stdbool.h>
 6 
 7 
 8 int Insert_search(int *a, int key, int n)
 9 {
10     int pos, low, high;
11     low = 0,high = n - 1;
12     while(low <= high){
13         pos = ((key - a[low]) * (high - low )) / (a[high] - a[low]) + low;
14         if(a[pos] < key){
15             low = pos + 1;
16         } else if(a[pos] == key){
17             return pos;
18         } else{
19             high = pos - 1;
20         }
21     }
22     return -1;
23 }
24 
25 int main()
26 {
27     
28     int a[13] = {5,15,19,20,25,31,38,41,45,49,52,55,57};
29     int k;
30     printf("请输入要查找的数字:\n");
31     scanf("%d",&k);
32     int pos = Insert_search(a,k,13);
33     if(pos != -1)
34         printf("在数组的第%d个位置找到元素:%d\n",pos + 1,k);
35     else
36         printf("未在数组中找到元素:%d\n",k);
37     return 0;
38 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值