1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| public class BinarySearch { public static int binarySearch(int[] array, int target) { int startIndex = 0, endIndex = array.length - 1, middleIndex = (endIndex - startIndex) / 2 + startIndex; while(startIndex <= endIndex) { middleIndex = (endIndex - startIndex) / 2 + startIndex; if (array[middleIndex] == target) { return middleIndex; } else if (array[middleIndex] < target) { startIndex = middleIndex + 1; } else { endIndex = middleIndex - 1; } } return -1; } public static void main(String[] args) { int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; System.out.println(BinarySearch.binarySearch(a, 1)); System.out.println(BinarySearch.binarySearch(a, 2)); System.out.println(BinarySearch.binarySearch(a, 3)); System.out.println(BinarySearch.binarySearch(a, 4)); System.out.println(BinarySearch.binarySearch(a, 5)); System.out.println(BinarySearch.binarySearch(a, 6)); System.out.println(BinarySearch.binarySearch(a, 7)); System.out.println(BinarySearch.binarySearch(a, 8)); System.out.println(BinarySearch.binarySearch(a, 9)); System.out.println(BinarySearch.binarySearch(a, 10)); System.out.println(BinarySearch.binarySearch(a, 11)); }
}
|