码迷,mamicode.com
首页 > Windows程序 > 详细

C# 二分查找

时间:2015-01-15 20:24:59      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

        /// <summary>
        /// 二分查找
        /// </summary>
        /// <param name="arr">数组</param>
        /// <param name="low">开始索引 0</param>
        /// <param name="hight">结束索引 </param>
        /// <param name="key">要查找的对象</param>
        /// <returns>对象所在的索引位置</returns>
        public static int BinarySearch(int[] arr ,int low, int hight,int key)
        {
            int mid = (low + hight) / 2;
            if (low>hight)
            {
                return -1;
            }
            else
            {
                if (arr[mid] == key)
                {
                    return mid;
                }
                else if(arr[mid] > key)
                {
                    return BinarySearch(arr, low, mid - 1, key);
                }
                else
                {
                    return BinarySearch(arr, mid + 1, hight, key);
                }
            }

        }



    int[] y = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int rr = BinarySearch(y, 0, y.Length - 1, 5);
            Console.Write(rr);

            Console.Read();

C# 二分查找

标签:

原文地址:http://blog.csdn.net/dingxl555/article/details/42745021

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!