网上二分查找法大部分是使用循环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;
}