C#算法 选择排序

C# 选择排序

选择排序的原理,第一次从数组中选出最小的数,将它放在数组的第一位置,第二次再从数组中选出最小的数,将它放置在第二个位置,以后每次都选出最小的数,按照上边的排序方式,放置在数组中合适的位置,这样到最后选出的数就是有序的。

        static void Main(string[] args)
        {
            List<int> list = new List<int>() { 27, 82, 7, 52 };//72, 54, 59, 30, 31, 78, 2, 77, 82, 72
            int temp = 0;
            int minIndex = 0;
            for (int i = 0; i < list.Count; i++)
            {
                minIndex = i;
                for (int j = i; j < list.Count; j++)
                {
                    //注意这里比较的是list[minIndex]
                    if (list[j] < list[minIndex])
                    {
                        minIndex = j;
                    }
                }
                temp = list[minIndex];
                list[minIndex] = list[i];
                list[i] = temp;
            }
            foreach (var item in list)
            {
                Console.Write(string.Format("{0} ", item));
            }
            Console.WriteLine();
            Console.ReadLine();
        }

 

posted @ 2016-08-18 08:22  iDennis  阅读(259)  评论(0编辑  收藏  举报