数据结构之插值查找

数据结构之--插值查找

定义:插值查找就是把要查找的关键字key与查找表中最大和最小记录的关键字比较后的查找方法,其核心就在于插值的计算公式(key-a[low])/(a[high]-a[low])

图解

时间复杂度:只是把折半的算法由mid=(low+high)/2变为了(mid=low+(high-low)*(key-a[low])/(a[high]-a[low])),所以时间复杂度还是为与普通折半查找一样为:O(logn)。

 

#include<stdio.h>

int Binary_Search(int *a,int n,int key){

  int low,mid,high;

  low = 1;                         /*定义最低下表为记录首位*/

  high = n;                         /*定义最高下表为记录末位*/

  while(low<high){

    mid=low+(key-a[low])*(high-low)/(a[high]-a[low]);  /*折半*/

    if(a[mid]<key)                    /*若查找值比中值小*/

      low=mid+1;                  /*最高下标调整到中位下标小一位*/

    else if(a[mid]>key)                 /*若查找值比中值大*/

      high=mid-1;                 /*最低下标调整到中值位下标大一位*/

    else

      return mid;                  /*若相等说明mid即为查找到的位置*/

  }

  return 0;

}

void main(){

  int num[] = {0,1,26,24,35,47,59,62,73,88,99};

  int result = Binary_Search(num,sizeof(num)/sizeof(num[0]),62);

  printf("查找结果为:%d\n",result);

}

 

运行结果为:

posted @ 2015-08-08 22:23  依凡王子  阅读(425)  评论(0编辑  收藏  举报