Binary search of a sorted array

前端 未结 6 971
南方客
南方客 2021-02-04 10:04

I am trying to search a descending sorted array using this binary search code. However, after I sort it, and try to search, it doesn\'t come back with any result, just a loading

6条回答
  •  后悔当初
    2021-02-04 10:46

    Its worked for me

    public static int search(int[] arr, int value)
    {
        Debug.Assert(arr.Length>0);
        var left = 0;
        var right = arr.Length - 1;
    
        while (((right - left)/2) > 0)
        {
            var middle = left + (right - left)/2;
            if (arr[middle] < value)
                left = middle + 1;
            else
                right = middle;
        }
        return arr[left] >= value ? left : right;
    }
    

提交回复
热议问题