Csharp递归和循环实现折半查找

  static bool whilehalf(int n)
        {
            int low = 0;  //低位
            int hight = arr.Length - 1;   //高位
            int c = (hight + low)/2;
            while(low <= hight)
            {
                if(n> arr[c])
                {
                    low = c + 1;
                }else if(n < arr[c])
                {
                    hight = c - 1;
                }else if(n == arr[c])
                {
                    Console.WriteLine("找到");
                    return true;
                }
                c = (hight + low)/2;
            }
            return false;
        }

 

 static bool rechalf(int l, int h, int c, int n)
        {
            if(l> h)
            {
                return false;
            }else  if(arr[c] > n)
            {
                h = c - 1;
                c = (h + l) / 2;
                return rechalf(l, h, c, n);
            }else if(arr[c]< n)
            {
                l = c + 1;
                c = (h + l) / 2;
                return rechalf(l, h, c, n);
            }
            else
            {
                return true;
            }
        }

 

posted @ 2015-11-16 21:03  狂奔的老鳖  阅读(1575)  评论(0编辑  收藏  举报