菜鸡笔记之——插值查找
插值查找:
插值查找是二分查找的另一种改进,二分查找的分割点是每一段的中点,斐波那契查找的分割点是黄金分割点,而插值查找也有它独特的分割方式。二分查找或斐波那契查找每次分割都是按照固定的规则分割下去,或者说他们每次分割后的两段的比例是一样的,这样没有办法根据查找值target来调整每次分割后的比例,算法科学家提出一种新方法:
二分查找的分割点为mid = (high+low)/2,也可以写成mid = low + (high-mid)*(1/2),将这个(1/2)改写为(target-a[low])/(a[high]-a[low]),让它与目标值target挂钩,这样在分割时能让分割点mid与target相适应并作出新的调整。
前提:序列有序,(最好能满足数据均匀分布)
插值查找与二分查找几乎一模一样,只是在mid迭代语句那里稍有不同。
代码实现(插值查找):
# include <stdio.h>
# include <stdlib.h>
int main(void)
{
int a[1000];
int N;
printf("the length of the array:");
scanf("%d",&N);
printf("enter the number:\n");
for (int i = 0;i<N;i++)
{
scanf("%d",&a[i]);
}
/*insert search*/
int target;
printf("enter the target number:");
scanf("%d",&target);
int insertsearch(int *,int,int);
int result = insertsearch(a,N,target);
printf("%d is the %dth number\n",target,result+1);
return 0;
}
/*
**function: insertsearch
**description: finding the target number from the array by Insert Search
**parameter 1: the name of the array
**parameter 2: the length of the array
**parameter 3: the number which you want to find
**return: the subscript of the target number in the array
*/
int insertsearch(int * a,int N,int target)
{
int low = 0,high = N-1,mid;
while (low<high)
{
mid = low+(high-low)*(target-a[low])/(a[high]-a[low]);
if (target==a[mid])
{
return mid;
}
else if (target<a[mid])
{
high = mid-1;
}
else if (target>a[mid])
{
low = mid+1;
}
}
printf("can not find this number!\n");
exit(0);
}
运行示例: