二分查找法(Java实现)

package sort;

import java.util.Arrays;

public class SearchUtils {
    public static void main(String[] args) {
        int[] arr = { 54, 26, 93, 17, 77, 31, 44, 55, 20 };
        // 二分查找要求数组有序
        SortUtils.quickSort(arr, 0, arr.length - 1);
        System.out.println(binarySearch(arr, 55));
        System.out.println(binarySearch2(arr, 78));
    }

    // 二分查找————递归实现
    public static boolean binarySearch2(int[] arr, int item) {
        int first = 0;
        int last = arr.length - 1;
        if (first >= last) {
            return false;
        } else {
            int mid = (first + last) / 2;
            if (arr[mid] == item) {
                return true;
            } else if (arr[mid] > item) {
                return binarySearch(Arrays.copyOfRange(arr, first, mid - 1), item);
            } else {
                return binarySearch(Arrays.copyOfRange(arr, mid + 1, last), item);
            }
        }
    }

    // 二分查找————非递归实现
    public static boolean binarySearch(int[] arr, int item) {
        int first = 0;
        int last = arr.length - 1;
        while (first <= last) {
            int mid = (first + last) / 2;
            if (arr[mid] == item) {
                return true;
            } else if (arr[mid] > item) {
                last = mid - 1;
            } else {
                first = mid + 1;
            }
        }
        return false;
    }
}

 

posted @ 2018-11-12 15:51  人工智能之路上的菜鸡  阅读(471)  评论(0编辑  收藏  举报