欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

二分查找【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 );
}
}

上一篇: PAT A1131. Subway Map (30)

下一篇: