当前位置:网站首页>插值查找和折半(二分)查找
插值查找和折半(二分)查找
2022-06-22 18:28:00 【单单一个越字】
插值查找
#include <stdio.h>
int bin_search( int str[], int n, int key )
{
int low, high, mid;
low = 0;
high = n-1;
while( low <= high )
{
mid = low + (key-a[low]/a[high]-a[low])*(high-low); // 插值查找的唯一不同点
if( str[mid] == key )
{
return mid;
}
if( str[mid] < key )
{
low = mid + 1;
}
if( str[mid] > key )
{
high = mid - 1;
}
}
return -1;
}
int main()
{
int str[11] = {
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89};
int n, addr;
printf("请输入待查找的关键字: ");
scanf("%d", &n);
addr = bin_search(str, 11, n);
if( -1 != addr )
{
printf("查找成功,可喜可贺,可口可乐! 关键字 %d 所在的位置是: %d\n", n, addr);
}
else
{
printf("查找失败!\n");
}
return 0;
}
折半(二分)查找:
#include<stdio.h>
int BinSearch(int arr[],int len,int key) //折半查找法(二分法)
{
int low=0; //定义初始最小
int high=len-1; //定义初始最大
int mid; //定义中间值
while(low<=high)
{
mid=(low+high)/2; //找中间值
if(key==arr[mid]) //判断min与key是否相等
return mid;
else if(key>arr[mid]) //如果key>mid 则新区间为[mid+1,high]
low=mid+1;
else //如果key<mid 则新区间为[low,mid-1]
high=mid-1;
}
return -1; //如果数组中无目标值key,则返回 -1 ;
}
int main()
{
int arr[]={
1,2,3,4,5,6,7,8,9,10,11}; //首先要对数组arr进行排序
printf("%d \n",BinSearch(arr,(sizeof(arr)/sizeof(arr[0])),7));
return 0;
}
边栏推荐
猜你喜欢

Experiment 7 trigger

小波变换db4进行四层分解及其信号重构—matlab分析及C语言实现

技术管理进阶——你了解成长的全貌吗?

Solution of off grid pin in Altium Designer

C #, introductory tutorial -- a little knowledge about function parameter ref and source program

Solution de pin hors grille dans altium designer

YARN笔记

what? Homekit, Micah, aqara and other ecosystems can also be linked with tmall elf ecology through zhiting?

故障分析 | 从 data_free 异常说起

Modify the antd tree component so that its subclasses are arranged horizontally.
随机推荐
Compilation error: /usr/bin/ld: /usr/local/lib/libgflags a(gflags.cc.o): relocation R_ X86_ 64_ 32S against `. rodata‘
The array objects are filled in one by one according to the ID (fill Arr1 into arr2)
Teachers, I want to ask you a question. I run flinkcdc locally to synchronize MySQL data. The timestamp field parsing is normal,
小波变换db4进行四层分解及其信号重构—matlab分析及C语言实现
MySQL约束
lua--数据类型、变量、循环、函数、运算符的使用
常用技术注解
详解openGauss多线程架构启动过程
Ts as const
Openpnp使用过程的一些问题记录
给对象赋值
插槽里如何判断text为数组
误用append案例一则
Openpnp debugging ------ 0816 Feida Tui 0402 taping
Calendar control programming
Take the file name in the zip package
Digital business cloud: build a digital supply chain system to enable enterprises to optimize and upgrade their logistics supply chain
0.1-----用AD画PCB的流程
Human Pose Estimation浅述
0.0 - how can SolidWorks be uninstalled cleanly?