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
| package com.test.algorithm;
public class BinarySearch {
public static int binarySearch(int[] arr, int des) { int low = 0; int height = arr.length - 1; while (low <= height) { int mid = (low + height) / 2; if (des == arr[mid]) { return mid; } else if (des < arr[mid]) { height = mid - 1; } else { low = mid + 1; } } return -1; }
private static int binarySearch(int[] arr, int des, int start, int end) { int mid = (start + end) / 2; if (des < arr[start] || des > arr[end] || start > end) { return -1; } if (des < arr[mid]) { return binarySearch(arr, des, start, mid - 1); } else if (des > arr[mid]) { return binarySearch(arr, des, mid + 1, end); } else { return mid; } }
public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6}; System.out.println(binarySearch(arr, 4)); } }
|