使用二进制搜索查找数字的最大索引出现

Find the largest index occurrence of a number using binary search

此代码生成一个随机数,将其按升序排序并进行二进制搜索以找到目标值。我的问题是如何修改此代码以找到给定目标的最大索引。例如数组有 { 1, 2 , 3, 5, 5, 5, 5},目标是 5,所以输出应该是 6 而不是 3。谢谢。

    import java.util.*;
    public class Sort
    {
        public static void main(String args[])
        {
            Scanner in = new Scanner(System.in);
            System.out.print("How many numbers do you want? ");
            int howMany = in.nextInt();
            int [] myArray =  getSortedRandomArray(howMany);
            System.out.print("\nFor what value would you like to search? ");
            int target = in.nextInt();
            int index = bsearch ( myArray, target);
            if (index >= 0)
            {
                System.out.println("The value " + target + " occurs at index " + index);
            }
            else
            {
                System.out.println("The value " + target + " does not occur in the array. ");
            }   
        }

  public static int bsearch(int[] arr, int key)
    {
    int lo = 0, hi = arr.length - 1;
    {
        while (lo < hi) 
        {
            int mid = (lo + hi) / 2;
            if (arr[mid] <= key)
                lo = mid + 1;
            if (arr[mid] > key)
                hi = mid;
        }
        if (arr[lo] == key) {
            return lo;
        }
        else if ((arr[lo] != key) && (arr[lo-1] == key)){
            return lo - 1;
        }
        else{
        System.out.print("The value " + key + " does not occur in the array. "); 
    } 
        return -1 ;
    } 
   public static int[] getSortedRandomArray (int howMany)
    {
        int[] returnMe = new int [howMany];
        Random rand = new Random();
        for (int i = 0; i < howMany ; i++) 
            returnMe[i] = rand.nextInt(Integer.MAX_VALUE) + 1;
        for (int i = 1; i <= (howMany - 1); i++)
        {
            for (int j = 0; j <= howMany - i -1; j++)
            {
                int tmp = 0;
                if (returnMe[j] > returnMe[j+1])
                {
                    tmp = returnMe[j];
                    returnMe[j] = returnMe[j + 1];
                    returnMe[j + 1] = tmp; 
                }   
            }  
        }
        System.out.print("Here is a random sorted array: ");
        for ( int i = 0; i < howMany; i++)
            System.out.print(returnMe[i] + " ");     
        return returnMe;
    }

如果稍微更新一下 bsearch 算法,您可以要求它递归地寻找更高的匹配项。然而,这是否比线性循环更有效取决于输入数组的样子。

public static int bsearch(int[] arr, int key, int lo, int hi) {
    while (lo <= hi) {
        int mid = (lo + hi) / 2;
        if (arr[mid] == key) {
            System.out.println("The value " + key + " is found at " + mid);
            int higherResult = bsearch(arr, key, mid + 1, hi);
            if (higherResult < 0) {
                return mid;
            }
            return higherResult;
        }
        if (arr[mid] < key) {
            lo = mid + 1;
        } else {
            hi = mid - 1;
        }
    }
    return -1;
}

您可以像这样修改二进制搜索算法代码来做到这一点:

 public static int bsearch(int[] arr, int key) {
    int lo = 0, hi = arr.length - 1;
    while (lo < hi) {
        int mid = (lo + hi) / 2;
        if (arr[mid] <= key)
            lo = mid + 1;
        if (arr[mid] > key)
            hi = mid;
    }

    if (arr[lo] == key) {
        return lo;
    }
    else {
        return lo - 1;
    }
}

此代码会搜索第一个大于关键字的数字。这可以是任何数字,6 或 10000,没关系。如您所见,如果 arr[mid] 等于 key,代码仍将 运行 在区间 [mid, hi] 上。为什么那两个 returns 最后呢?好吧,如果输入数组就像你给的那个,lo 将结束是最后 5 个的索引,但是如果我们在输入数组的末尾添加另一个数字,lo 将是最后 5 个数字后面的索引。因此,我们有 2 个不同的案例。

此外,您不能像其他答案那样使用线性循环来完成它,因为这会将算法减少到 O(n),并且它最终只是对简化数组的线性搜索。