文件说明: 二分法查找目标数据所在数组中的位置索引 演示程序 当前版本: 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;
}