您的位置:首页 > 文旅 > 旅游 > 5118网站_国家大宗商品交易平台_武汉seo公司哪家好_每日新闻

5118网站_国家大宗商品交易平台_武汉seo公司哪家好_每日新闻

2024/10/10 10:03:10 来源:https://blog.csdn.net/qq_39524140/article/details/142750293  浏览:    关键词:5118网站_国家大宗商品交易平台_武汉seo公司哪家好_每日新闻
5118网站_国家大宗商品交易平台_武汉seo公司哪家好_每日新闻

网上二分查找法大部分是使用循环while来实现的,我感到不好理解,使用迭代法for来实现。

代码如下:

代码还需要优化,初版如下。

#include <stdio.h>
typedef unsigned char uint8;
typedef unsigned int uint32;
#define ARRAY_MAX_LEN (5000)
uint8 binary_search(const uint32 * array, uint32 len, uint32 num, uint32 * index)
{uint32 index_left = 0;uint32 index_right = 0;uint32 index_mid = 0;uint32 j = 0;uint32 count = 0;if ((len > ARRAY_MAX_LEN) ||(len == 0)){return 1;}index_right = len - 1;for (j = 0; j < len - 1; j++){count = j;index_mid = (index_left + index_right) / 2;if (num == *(array+index_mid)){*index = index_mid;printf("count = %d\n", count);return 0;}else if (num < *(array + index_mid)){index_right = index_mid;}else{index_left = index_mid;}if (index_left + 1 >= index_right){return 1;}}return 1;
}uint8 main(void)
{uint32 arr[ARRAY_MAX_LEN] = {1,2,  3, 4, 5, 6, 7, 8,  9, 10, 11, 12,13,14, 15,16, 17, 18, 19, 20, };uint32 len = 20;uint32 index;uint32 count;uint8 result = binary_search(arr, len, 6, &index);printf("result = %d\n", result);printf("index = %d\n", index);printf(" arr[index] = %d\n", arr[index]);printf(" find 6\n" );return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com