Binary search of a sorted array

前端 未结 6 981
南方客
南方客 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:54

    This is one correct :

    if target< mynumbers[mid] then you have to take last to mid-1, because we have to search in lower range i.e. first to mid-1

    while (first<=last)
            {
                mid = (first + last) / 2;
                if (target == mynumbers[mid])
                Label11.Text = "Target " + item + " was found at index " + mynumbers[mid];
    
                else if (target < mynumbers[mid])
                    last = mid - 1;
                else (target > mynumbers[mid])
                    first = mid + 1;
    
                }
    

提交回复
热议问题