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 ) );