首页 > 代码库 > 二分查找法(仅供个人拾遗)

二分查找法(仅供个人拾遗)

二分查找法:

 private static void Main(string[] args)        {            int[] data = http://www.mamicode.com/new int[10];            for (int i = 0; i < 10; i++)            {                data[i] = i + 3;            }            for (int i = 0; i < 10; i++)            {                Console.Write(data[i] + " ");            }            Console.WriteLine();            int ii = BinarySearch.Search(data, 9);            Console.WriteLine(ii);        }

 

public static class BinarySearch    {        public static int  Search(int[] data,int val)        {            // if data is null ,return -1            if (data.Length <= 0)            {                return -1;            }            int low = 0;            int high = data.Length - 1;            while (low <= high)            {                int middle = (low + high) / 2;                if (data[middle] == val)                {                     return middle;                 }                else if (data[middle] <val)                {                    low = middle + 1;                }                else                {                    high = middle - 1;                }            }            return -1;        }    }

 

二分查找法(仅供个人拾遗)