扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
这篇文章主要介绍C经典算法之二分查找法的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
成都创新互联是一家专业提供焦作企业网站建设,专注与成都网站设计、做网站、HTML5建站、小程序制作等业务。10年已为焦作众多企业、政府机构等服务。创新互联专业的建站公司优惠进行中。
C经典算法之二分查找法
1.根据key查找所在数组的位置
#include/* key = 9; 1 2 3 4 5 6 7 8 arr 3, 4, 5, 7, 9 , 11, 21, 23 low = 1 mid = (low + high)/2 = 4 high = 8; one arr[mid] = 7 < 9; so low = mid + 1 = 5; high = 8; mid = (low + high)/2 = 6 two arr[mid] = 11 > 9 so low = 5 , high = mid - 1 = 5 mid = 5; arr[mid] = 9 == key if(key = 10) low = mid + 1 > high */ int main(int argc, const char * argv[]) { int findByHalf(int arr[], int len, int key); int arr[] = {3, 4 , 5, 7, 9 , 11, 21, 23}; int len = sizeof(arr)/sizeof(int); int index = findByHalf(arr, len, 88); printf("index = %d\n", index); return 0; } int findByHalf(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]) { low = mid + 1; //左边查找 }else if (key > arr[mid]) { high = mid - 1; }else{ return mid; } } return -1; }
2.插入一个数,得到其所在数组的位置
#include/* key = 9; 1 2 3 4 5 6 7 8 arr 3, 4, 5, 7, 9 , 11, 21, 23 low = 1 mid = (low + high)/2 = 4 high = 8; one arr[mid] = 7 < 9; so low = mid + 1 = 5; high = 8; mid = (low + high)/2 = 6 two arr[mid] = 11 > 9 so low = 5 , high = mid - 1 = 5 mid = 5; arr[mid] = 9 == key if(key = 10) low = mid + 1 > high */ int main(int argc, const char * argv[]) { int findByHalf(int arr[], int len, int key); int arr[] = {3, 4 , 5, 7, 9 , 11, 21, 23}; int len = sizeof(arr)/sizeof(int); int index = findByHalf(arr, len, 88); printf("index = %d\n", index); return 0; } int insertByHalf(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]) { low = mid + 1; //左边查找 }else if (key > arr[mid]) { high = mid - 1; }else{ //如果arr[mid] == key //就把key插入到这个数的后面 return mid + 1; } } //如果low > high 说明 key > arr[mid]; //就把key插入到low对应的 这个数的位置 return low; }
以上是“C经典算法之二分查找法的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流