Binary search of a sorted array

前端 未结 6 1051
南方客
南方客 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 11:01

    //this works fine with these Test cases    
    // has to check if (target == mynumbers[mid])    
    // this is for an array with ascending order.
    class Program
    {
    
        static void Main(string[] args)
        {
            // TEST cases:
            // for 8: item 8 was not found
            // for 4: item 4 found at Position 3
            // for 1: item 1 found at position 0
            // for 0: item 0 was not found
    
    
            int target =8;
            int searchkey = target;
    
            int[] mynumbers = { 1, 2, 3, 4, 5 };
    
            int mid=0, first = 0, last = mynumbers.Length - 1;
    
            bool found = false;
    
            //for a sorted array with ascending values
            while (!found && first <= last)
            {
                mid = (first + last) / 2;
    
                if (target == mynumbers[mid])
                    found = true;
                else
                {
    
                    if (target > mynumbers[mid])
                    {
                        first = mid + 1;
                    }
    
                    if (target < mynumbers[mid])
                    {
                        last = mid - 1;
                    }
    
                }
    
            }
    
            String foundmsg = found
                ? "Item " + searchkey + " was found at position " + mid
                : "Item " + searchkey + " was not found";
            Console.WriteLine(foundmsg);
         }
    }
    

提交回复
热议问题