二分法使用方法调用的练习--修改

 class Program
    {
        /// <summary>
        /// 二分法查找
        /// </summary>
        /// <param name="s">要查找的数</param>
        /// <param name="arr">有序的数组</param>
        /// <returns>查找数的索引</returns>
        static int Search(int s,int[] arr)
        {
            int a = 0;
            int b = arr.Length - 1;
            while (a <= b)
            {
                int c = (a + b )/2;
                if (arr[c] == s)
                {
                    return c;
                }
                else if (arr[c] > s)
                    b = c - 1;
                else
                    a = c + 1;
            }
            return -1;
        }

        static void Main(string[] args)
        {
            Console.WriteLine("数组为:");
            int[] arr1 = new int []{1,3,4,5,6,9,13,15,18,29,34,39,40,45,48,57,59,64};
            foreach (int i in arr1)
                Console.Write(i + " ");
            Console.WriteLine("\n您要查找的数:");
            int s = Convert.ToInt32(Console.ReadLine());
            int m = Search(s,arr1);
            if (m >= 0)
            {
                Console.WriteLine("您要查找的数为第" + (m + 1) + "位!");
            }
            else
                Console.WriteLine("您要查找的数字不存在!");
            Console.ReadLine();
        }
    }

 

posted @ 2015-08-12 23:01  WhyToHow  阅读(261)  评论(0编辑  收藏  举报