二分查找【c语言】
程序员文章站
2024-03-17 14:51:58
...
#include <stdio.h>
int halfSearch( int arr[], int num, int size ) {
int min = 0, max = ( size - 1), mid;
if ( size == 0 ) { return -1; }
while ( 1 ) {
// 1. when the boundary is "min" or "max"
if ( num == arr[ min ] ) { return min ; }
if ( num == arr[ max ] ) { return max ; }
// 2. check the not found.
if ( 1 == ( max - min ) ) { return -1; }
// 3. reset the middle.
mid = ( max - min ) / 2 + min;
// 4. check num is middle, and reset the boundary "min" or "max"
if ( num == arr[ mid ] ) { return mid; }
else if ( num > arr[ mid ] ) {
min = mid;
} else {
max = mid;
}
}
return -1;
}
void main(void) {
int arr[] = {1,3,4,6,7,8,8,9,44,345,666}; //
int idx = halfSearch( arr, 9 , sizeof( arr ) / sizeof( int ) );
if ( idx == -1 ) {
printf( "未找到!\n" );
} else {
printf( "找到数据%d,下标%d \n", arr[idx], idx );
}
}