c语言查表CODE,[原创]分享一个二分(折半)查表算法查找数据区间索引的算法代码与C语言例程...

文件说明: 二分法查找目标数据所在数组中的位置索引 演示程序 当前版本: 1.0.0 程序作者: foxpro2005 创建日期: 2020-04-12

算法一:所在区间索引值(0~(table_size-1)向下原则),强制索引在上下范围内

int table_lookup(int *p_table, int table_size, int x)

{

int mid, btm = 0, top = table_size - 1;

if (x < p_table[btm + 1]) { // 超出下限,锁定在btm索引值范围

return btm;

}

else if (x < p_table[top]) { // 在表格范围内

for ( ;(top - btm) > 1; ) // 2分法查找区间, ((top - btm) != 1)

{

mid = (btm + top) / 2; // 折半计算(除以2)

if (x > p_table[mid]) {

btm = mid;

}

else if (x < p_table[mid]) {

top = mid;

}

else {

return mid; // 正好等于mid位所在值

}

}

return btm; // 找到一个区间,并返回这个区间的开始索引值(以向下原则)

}

else { // 超出上限,锁定在top索引值范围

return top;

}

return -2;

}

算法二:所在区间索引值(0~(table_size-1)向下原则), -2:错误, -1:超出下限, table_size:超出上限

int table_lookup2(int *p_table, int table_size, int x)

{

int mid, btm = 1, top = table_size - 1;

if (x < p_table[0]) { // 超出下限

return -1; // 返回-1

}

else if (x < p_table[1]) { // 区间: 0 ~ 1

return 0; // 返回表头0

}

else if (x < p_table[top]) { // 区间: 1 ~ top

for( ;(top - btm) > 1; ) // 2分法查找区间, ((top - btm) != 1)

{

mid = (btm + top) / 2; // 折半计算(除以2)

if (x > p_table[mid]) {

btm = mid;

}

else if (x < p_table[mid]) {

top = mid;

}

else {

return mid; // 正好等于mid位所在的值

}

}

return btm; // 找到一个区间,并返回这个区间的开始索引值(向下原则)

}

else if (x == p_table[top]) { // 区间: top

return top; // 返回表尾top(table_size - 1)

}

else { // 超出上限

return table_size; // 返回table_size

}

return -2; // 返回错误-2

}

以下是测试程序:

int Table[15]={ 3,9,16,20,26,31,38,42,47,51,58,66,73,87,98 };

int main(void)

{

int i,x;

printf("表格数据:\r\n");

for(i=0; i < (sizeof(Table) / sizeof(Table[0])); i++)

{

if(i==0)

printf("Table={%d",Table[i]);

else

printf(",%d",Table[i]);

}

printf("}\r\n");

printf("输入\"-1\"结束!\r\n");

while(1)

{

printf("\r\n请输入一个数据: ");

scanf("%d", &x);

if(x == -1)

break;

else{

printf("[算法一]: %d's index is %d\r\n",x,table_lookup(Table, (sizeof(Table) / sizeof(Table[0])), x));

printf("[算法二]: %d's index is %d\r\n",x,table_lookup2(Table, (sizeof(Table) / sizeof(Table[0])), x));

}

}

return -1;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值