蓝色天空网 · mbsky.com

查找:线性、二分与插值

先满足排序和数值范围条件,再谈渐近表现。

逐步查看固定输入下的数据变化。这里回放本地C程序的实际结果;下载源码后可修改输入并重新编译。

实际运行范围

当前固定输入有 69 项断言通过。本次实验创建的动态节点已全部释放。当前结果对应本章固定输入,改变输入后请重新编译核对。

编译器:Zig 0.14.1 cc;标准:C11;本轮环境:Windows。

下载本章入口 · 共享实现 · 接口定义 · 断言与记录

编译:zig cc -std=c11 -Wall -Wextra -Werror -pedantic c-dsa-search-techniques.c dsa.c -o demo.exe,再运行demo.exe。

本章完整入口

#include "test_support.h"

int main(void){
 puts("MBSKY | mbsky.com | independently authored C11 case");
int a[]={10,20,30,40,50,60,70,80,90};size_t steps;CHECK(linear_find(a,9,50,&steps)==4&&steps==5);int counts[3]={(int)steps,0,0};CHECK(binary_find(a,9,50,&steps)==4);counts[1]=(int)steps;CHECK(interpolation_find(a,9,50,&steps)==4);counts[2]=(int)steps;state("actual-probes-target50",counts,3);CHECK(interpolation_find(a,9,100,&steps)==9);CHECK(interpolation_find(NULL,0,5,&steps)==0);CHECK(binary_find(NULL,0,5,&steps)==0);CHECK(linear_find(NULL,0,5,&steps)==0);int repeated[]={7,7,7};CHECK(interpolation_find(repeated,3,7,&steps)==0);CHECK(interpolation_find(repeated,3,6,&steps)==3);CHECK(binary_find(repeated,3,7,&steps)==0);int extreme[]={INT_MIN,0,INT_MAX};CHECK(interpolation_find(extreme,3,INT_MAX,&steps)==2);CHECK(interpolation_find(extreme,3,INT_MIN,&steps)==0);state("extreme-safe-range",extreme,3);for(int target=-12;target<=12;++target){int sorted[]={-10,-5,0,0,3,8,12};size_t first=linear_find(sorted,7,target,&steps),b=binary_find(sorted,7,target,&steps),c=interpolation_find(sorted,7,target,&steps);CHECK(b==first);CHECK((c==7)==(first==7));if(c<7)CHECK(sorted[c]==target);}
 return finish();
}