本帖最后由 清秋 于 2011-11-10 17:16 编辑
- /*
- 折半查找
- */
- class HalfSearch
- {
- public static void main(String[] args)
- {
- int arr[] = {1,3,5,6,7,9,12,24};
- //System.out.println(halfSearch( arr, 0, arr.length, 2 ));
- int num = halfSearch( arr, 23 );
- System.out.println(num);
- }
-
- private static int halfSearch ( int arr[], int key )
- {
- int left, right, mid;
- left = 0;
- right = arr.length - 1;
- while ( left < right )
- {
- mid = ( left + right ) / 2;
- if ( key == arr[mid] )
- {
- return mid;
- }
- else if ( key < arr[mid] )
- {
- right = mid;
- }
- else if ( key > arr[mid] )
- {
- left = mid;
- }
- }
- return -1;
- }
- }
复制代码 |