Find the largest value smaller than x in a sorted array

后端 未结 5 1450
不知归路
不知归路 2021-02-07 23:26

Suppose I have a sorted array of integers int[], and I want to search the closest smaller value to some input number.

for example if the array contains (1)

5条回答
  •  -上瘾入骨i
    2021-02-08 00:19

    Use Array.BinarySearch. If the input is in the list, it will return the index, and if not then it will return the complement of the index of the first larger value. You just invert the result and subtract one to get the index of the closest smaller value.

    int[] arr = { 1, 23, 57, 59, 120 };
    int index = Array.BinarySearch(arr, 109);
    if (index < 0)
    {
        index = ~index - 1;
    }
    if (index >= 0)
    {
        var result = arr[index];
    }
    

    Note that if you have an input smaller than the smallest element, you don't have a well-defined answer.

提交回复
热议问题