2013年9月11日 星期三

List 清單的排序、搜尋和插入


            //示範 List 清單的排序、搜尋和插入
            //http://msdn.microsoft.com/zh-tw/library/w4e7fxsh(v=vs.80).aspx
            List<string> dinosaurs = new List<string>();
            dinosaurs.Add("Pachycephalosaurus");
            dinosaurs.Add("Amargasaurus");
            dinosaurs.Add("Mamenchisaurus");
            dinosaurs.Add("Deinonychus");
            Console.WriteLine();
            foreach (string dinosaur in dinosaurs)
            {
                Console.WriteLine(dinosaur);
            }
            Console.WriteLine("\nSort");
            dinosaurs.Sort();
            Console.WriteLine();
            foreach (string dinosaur in dinosaurs)
            {
                Console.WriteLine(dinosaur);
            }
            int test = -1;
            test = ~test;    //補數運算 (~) -1 ==> 0 、 -9 ==> 8
            //傳回值
            //如果有找到 item,則為已排序的 List 中 item 之以零起始的索引,否則便為負數,此負數為大於 item 的下一個元素索引之位元補數,
            //或者,如果沒有更大的元素,則為 Count 的位元補數。 (List 必須已經依照比較子實作排序過,否則結果會不正確)
            Console.WriteLine("\nBinarySearch and Insert \"Coelophysis\":");
            int index = dinosaurs.BinarySearch("Coelophysis");
            if (index < 0)
            {
                //使用 Insert 方法插入
                dinosaurs.Insert(~index, "Coelophysis");
            }
            Console.WriteLine();
            foreach (string dinosaur in dinosaurs)
            {
                Console.WriteLine(dinosaur);
            }
            Console.WriteLine("\nBinarySearch and Insert \"Tyrannosaurus\":");
            index = dinosaurs.BinarySearch("Tyrannosaurus");
            if (index < 0)
            {
                dinosaurs.Insert(~index, "Tyrannosaurus");
            }
            Console.WriteLine();
            foreach (string dinosaur in dinosaurs)
            {
                Console.WriteLine(dinosaur);
            }
            Console.ReadKey();
            /* This code example produces the following output:
            Pachycephalosaurus
            Amargasaurus
            Mamenchisaurus
            Deinonychus
            Sort
            Amargasaurus
            Deinonychus
            Mamenchisaurus
            Pachycephalosaurus
            BinarySearch and Insert "Coelophysis":
            Amargasaurus
            Coelophysis    <-- ~-2 = 1
            Deinonychus
            Mamenchisaurus
            Pachycephalosaurus
            BinarySearch and Insert "Tyrannosaurus":
            Amargasaurus
            Coelophysis
            Deinonychus
            Mamenchisaurus
            Pachycephalosaurus
            Tyrannosaurus    <-- ~-6 = 5
            */

沒有留言:

張貼留言