庄生晓梦

庄生晓梦迷蝴蝶

博客园 首页 新随笔 联系 订阅 管理
#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 );
	}
}


已有 0 人发表留言,猛击->>这里<<-参与讨论


ITeye推荐



posted on 2012-05-21 09:20  qwop  阅读(168)  评论(0编辑  收藏  举报