数据结构与算法之美代码:二分查找2

目录

  • 二分查找的变形问题
  • 代码

二分查找的变形问题

数据结构与算法之美代码:二分查找2_第1张图片

代码

package com.athome.search;

public class BinarySearchDemo {
    public static void main(String[] args) {
        int[] arr ={1,3,4,5,6,8,8,8,11,18};
        int index1 = bsearch1(arr, arr.length, 8);
        int index2 = bsearch2(arr, arr.length, 8);
        int index3 = bsearch1(arr, arr.length, 11);
        int index4 = bsearch1(arr, arr.length, 6);
        System.out.println(index1);
        System.out.println(index2);
        System.out.println(index3);
        System.out.println(index4);


    }

    //变体一:查找第一个值等于给定值的元素
    public static int bsearch1(int[] a, int n, int value) {
        int low = 0;
        int high = n - 1;
        while (low <= high) {
            int mid =  low + ((high - low) >> 1);
            if (a[mid] > value) {
                high = mid - 1;
            } else if (a[mid] < value) {
                low = mid + 1;
            } else {
                if ((mid == 0) || (a[mid - 1] != value)) return mid;
                else high = mid - 1;
            }
        }
        return -1;
    }

    //变体二:查找最后一个值等于给定值的元素
    public static int bsearch2(int[] a, int n, int value) {
        int low = 0;
        int high = n - 1;
        while (low <= high) {
            int mid =  low + ((high - low) >> 1);
            if (a[mid] > value) {
                high = mid - 1;
            } else if (a[mid] < value) {
                low = mid + 1;
            } else {
                if ((mid == n - 1) || (a[mid + 1] != value)) return mid;
                else low = mid + 1;
            }
        }
        return -1;
    }


    //变体三:查找第一个大于等于给定值的元素
    public static  int bsearch3(int[] a, int n, int value) {
        int low = 0;
        int high = n - 1;
        while (low <= high) {
            int mid =  low + ((high - low) >> 1);
            if (a[mid] >= value) {
                if ((mid == 0) || (a[mid - 1] < value)) return mid;
                else high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return -1;
    }


    //变体四:查找最后一个小于等于给定值的元素
    public static int bsearch4(int[] a, int n, int value) {
        int low = 0;
        int high = n - 1;
        while (low <= high) {
            int mid =  low + ((high - low) >> 1);
            if (a[mid] > value) {
                high = mid - 1;
            } else {
                if ((mid == n - 1) || (a[mid + 1] > value)) return mid;
                else low = mid + 1;
            }
        }
        return -1;
    }



}

你可能感兴趣的:(数据结构与算法之美代码,java,算法,数据结构)