Page 46 数组Sort, Reverse, BinarySearch方法

namespace CH02
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] forSort = new int[]
            {
                1, 2, 3, 9, 8, 7, 6
            };

            System.Array.Sort(forSort);

            for (int i = 0; i < forSort.Length; i++)
            {
                System.Console.Write("{0} ", forSort[i]);
            }

            System.Console.WriteLine();

            // 将数组反向
            // System.Array.Reverse(forSort);
            // BinarySearch使用之前必须Sort
            // **************************************************************************************
            // 如何搜索的元素不存在,那么返回负值。使用取反运算符~index,会返回大于搜索值的第一个索引
            // **************************************************************************************
            int index = System.Array.BinarySearch(forSort, 1);

            for (int i = 0; i < forSort.Length; i++)
            {
                System.Console.Write("{0} ", forSort[i]);
            }
            System.Console.WriteLine("index: {0}", index);

            // Clear()不是删除数组的元素。而是将每个元素都设置成默认值。
            System.Array.Clear(forSort, 0, forSort.Length);
            for (int i = 0; i < forSort.Length; i++)
            {
                System.Console.Write("{0} ", forSort[i]);
            }

            System.Console.ReadKey(true);
        }
    }
}
posted @ 2011-11-29 15:04  jacky_j2ee  阅读(260)  评论(0编辑  收藏  举报