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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| public class TestBinarySearch { public static void main(String[] args) { int result = 0; int[] nums1 = {1, 2, 3, 4, 5, 6, 7, 8, 9}; result = binarySearch(nums1, 3); System.out.println(result);
int[] nums2 = {9, 8, 7, 6, 5, 4, 3, 2, 1}; result = binarySearch(nums2, 3); System.out.println(result);
int[] nums3 = {1, 8, 3, 6, 2, 9, 7, 4, 5}; result = binarySearch(nums3, 3); System.out.println(result); }
public static int binarySearch(int[] array, int a) { if (null == array || array.length == 0) { return -1; } boolean up = false; for (int i = 0; i < array.length - 1; i++) { if (array[i] < array[i+1]) { if (i+1 == array.length-1) { up = true; } } else if (array[i] > array[i + 1]) { if (i+1 == array.length - 1) { up = false; } } else { return -1; } } int minIndex = 0; int maxIndex = array.length - 1; int midIndex; while (minIndex <= maxIndex) { midIndex = (minIndex + maxIndex) / 2; if (array[midIndex] > a) { if (up) { maxIndex = midIndex-1; } else { minIndex = midIndex+1; } } else if (array[midIndex] < a) { if(up) { minIndex = midIndex+1; } else { maxIndex = midIndex-1; } } else { return midIndex; } } return -1; } }
|