- package algorithm;
- public class Search {
- public static void main(String[] args) {
- int[] array = { 20, 44, 48, 55, 62, 66, 74, 88, 93, 99 };
- int result = binarySearch(90, array);
- System.out.println(result);
- }
- //基本类型的线性查找
- public static int linearSearch(int target, int[] array) {
- for (int i = 0; i < array.length; i++) {
- if (array[i] == target)
- return i;
- }
- return -1;
- }
- //对象的情况的线性查找
- public static int linearSearch(Object target, Object[] array) {
- for (int i = 0; i < array.length; i++) {
- if (array[i].equals(target))
- return i;
- }
- return -1;
- }
- //基本类型的二分查找
- public static int binarySearch(int target, int[] array) {
- int low = 0;
- int high = array.length - 1;
- while (low <= high) {
- int middle = (low + high) / 2;
- if (array[middle] == target) {
- return middle;
- } else if (array[middle] < target) {
- low = middle + 1;
- } else
- high = middle - 1;
- System.out.println("low=" + low);
- System.out.println("high=" + high);
- System.out.println("middle=" + middle);
- System.out.println("====================");
- }
- return -1;
- }
- //对象情况下的二分查找
- public static int binarySearch(Object target, Object[] array) {
- int low = 0;
- int high = array.length - 1;
- while (low <= high) {
- int middle = (low + high) / 2;
- int result = ((Comparable) array[middle]).compareTo(target);
- if (result == 0) {
- return middle;
- } else if (result < 0) {
- low = middle + 1;
- } else
- high = middle - 1;
- }
- return -1;
- }
- }
结果:
low=5
high=9
middle=4
====================
low=8
high=9
middle=7
====================
low=8
high=7
middle=8
====================
-1
转载于:https://blog.51cto.com/huqianhao/954414