昨晚学习了折半查找法,今早起来练练手儿,看看记住没有
- #include <stdio.h>
- /**
- * 折半查找函数
- *
- * @param num 待查找的数组
- * @param length 数组的长度
- * @param keyValue 要查找的key值
- *
- * @return 返回key的位置
- */
- int searchNum(int num[],int length,int keyValue){
- //定义变量
- int low=0,high=length-1,middle;
-
- while (low<=high) {
- //给middle赋值
- middle=(low+high)/2;
- //当key>middle middle=low+1
- if(keyValue>num[middle]){
- low=middle+1;
- }
- //当key<middle middle=high-1
- else if(keyValue<num[middle]){
- high=middle-1;
- }
- //当key==middle,return middle
- else if(keyValue==num[middle]){
- return middle;
- }
- }
- return -1;
-
- }
- int main(int argc, const char * argv[]) {
- // 定义一个有序的已知数组
- int num[]={3,12,34,56,66,73,86,92,111,120};
- //调用查找函数,返回keyValue位置
- int index = searchNum(num, 10, 110);
- printf("%d\n",index);
- return 0;
- }
复制代码 |
|