java.util.Arrays

1: public static int binarySearch(int[] a, int key) {

2: int low = 0;

3: int high = a.length - 1;

4:

5: while (low <= high) {

6: int mid = (low + high) / 2;

7: int midVal = a[mid];

8:

9: if (midVal < key)

10: low = mid + 1

11: else if (midVal > key)

12: high = mid - 1;

13: else

14: return mid; // key found

15: }

16: return -(low + 1); // key not found.

17: }



6: int mid =(low + high) / 2;

int

low

high

low

high

int

ArrayIndexOutOfBoundsException

n

6: int mid = low + ((high - low) / 2);

6: int mid = (low + high) >>> 1;

>>>

6: mid = ((unsigned int)low + (unsigned int)high)) >> 1;

Update 17 Feb 2008

INTERNATIONAL STANDARD - ISO/IEC - 9899 - Second edition - 1999-12-01

know

Resources