A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 庭院深深深几许 金牌黑马   /  2019-4-17 11:33  /  842 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

[C#] 纯文本查看 复制代码
namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            int[] array = { 10, 25, 31, 36, 42, 49, 56, 71, 77, 88, 96, 100,111 };
            ShowSord(array);
            Console.Write("...........................");
            int returnIndex = TwoPointsSearch(array, 25, 0, array.Length - 1);
            Console.Write("数组元素{0}的索引为{1}", 25, returnIndex.ToString());
            Console.ReadKey();
        }
        /// 
        /// 输出数组所有元素
        /// 
        /// 
        private static void ShowSord(int[] array)
        {
            foreach (var num in array)
            {
                Console.Write($"{num} ");
            }
            Console.WriteLine();
            Console.Write("数组长度为{0}", array.Length.ToString());
            Console.WriteLine();
        }
        /// 
        /// 返回索引,不存在则返回-1
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static int TwoPointsSearch(int[] array,int data, int  leftIndex,int rightIndex)
        {
            int MiddleIndex = (leftIndex + rightIndex) / 2;
            if (leftIndex > rightIndex)
            {
                return -1;
            }
            //不存在返回-1;
            else
            {
                if (array[MiddleIndex] == data)
                {
                    return MiddleIndex;
                }
                else
                {
                    if (array[MiddleIndex] > data)
                    {
                      return  TwoPointsSearch(array, data, leftIndex, MiddleIndex-1);
                    }
                    else
                    {
                     return   TwoPointsSearch(array, data, MiddleIndex+1, rightIndex);
                    }
                }
            }
        }
    }
}

  输出:

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马