Array.BinarySearch()方法检索错误问题

其实这是一个很简单的问题,但是很多教材上都没有明确指出来,BinarySearch()方法的使用前提是所要检索的数组或者集合已经排序。

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{

    
    class Program
    {
        
        static void Show(int[] a)//遍历数组进行输出
        {
            foreach (int i in a)
            {
                Console.Write(i+" ");
            }
            Console.WriteLine("");
        }
        
        static void Main(string[] args)
        {
            int[] a = { 0, 28, 8, 7, 45, 5, 3, 4, 9, 1, 12, -1 };
            Show(a);
            Console.WriteLine("请输入要查找的数组元素IndexOf");
            int input = Convert.ToInt32(Console.ReadLine());//必须是ReadLine不能是Read
            Console.WriteLine("您输入的是:"+input);
            Console.WriteLine("您要查找的数在数组中的下标为:{0}", Array.IndexOf(a, input));
            Console.WriteLine(); Console.WriteLine();

            Console.WriteLine("请输入要查找的数组元素BinarySearch");
            int input2 = Convert.ToInt32(Console.ReadLine());//必须是ReadLine不能是Read
            Console.WriteLine("您输入的是:" + input2);
            Console.WriteLine("您要查找的数在数组中的下标为:{0}", Array.BinarySearch(a, input2));



            Console.WriteLine("排序后:");
            Array.Sort(a);
            Show(a);
            Console.WriteLine(); Console.WriteLine();

            //使用BinarySearch二分检索的前提是数组已经排序
            Console.WriteLine("请输入要查找的数组元素IndexOf");
            int input3 = Convert.ToInt32(Console.ReadLine());//必须是ReadLine不能是Read
            Console.WriteLine("您输入的是:" + input3);
            Console.WriteLine("您要查找的数在数组中的下标为:{0}", Array.IndexOf(a, input3));
            Console.WriteLine(); Console.WriteLine();

            Console.WriteLine("请输入要查找的数组元素BinarySearch");
            int input4 = Convert.ToInt32(Console.ReadLine());//必须是ReadLine不能是Read
            Console.WriteLine("您输入的是:" + input4);
            Console.WriteLine("您要查找的数在数组中的下标为:{0}", Array.BinarySearch(a, input4));
        }
    }
    


}
  
posted @ 2012-11-17 18:01  .NET~莫愁  阅读(264)  评论(0编辑  收藏  举报