菜鸡笔记值——插值查找

菜鸡笔记之——插值查找

插值查找:
插值查找是二分查找的另一种改进,二分查找的分割点是每一段的中点,斐波那契查找的分割点是黄金分割点,而插值查找也有它独特的分割方式。二分查找或斐波那契查找每次分割都是按照固定的规则分割下去,或者说他们每次分割后的两段的比例是一样的,这样没有办法根据查找值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);
}

运行示例:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值