在一个排好序的数组里怎么最快的查找到里面的一个元素,如果存在这个元素返回1,不存在返回0
应该是先和中间一个比较,如果大于就再到比中间数大的那个1半里找比较快吧,程序怎么实现呢,谢谢写出程序,
上次面试遇到这个问题却没写出来,哎。

解决方案 »

  1.   

    LZ讲的是二分查找吧!试试如下代码:
    假设数组为int[] a;
            private bool Find(int NowPos, int LeftAmt, int FindItem)
            {
                if (LeftAmt <=1)
                {
                    if (a[NowPos+LeftAmt] == FindItem)
                    {
                        return true;
                    }
                    return false;
                }
                if (a[NowPos] == FindItem)
                {
                    return true;
                }
                else
                {
                    LeftAmt -= LeftAmt / 2;
                    if (a[NowPos] < FindItem)
                    {
                        NowPos = NowPos + LeftAmt / 2;
                    }
                    else
                    {
                        NowPos = NowPos - LeftAmt / 2;
                    }
                    return Find(NowPos, LeftAmt, FindItem);
                }
            }
    调用该方法的表达式为:
    Find((a.Length - 1)/2, a.Length, 查找值);