C# 排序算法记录

    class Program
    {
        static void Main(string[] args)
        {
            var array = new[] { 11, 3, 24, 5, 0, 2, 4, 6, -1, 101, 101, 5 };

            //假设一个最小的值
            var minnum = array[0];
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i] < minnum)
                {
                    minnum = array[i];
                }

            }

            //假设一个最大的值
            var maxnum = array[0];
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i] > maxnum)
                {
                    maxnum = array[i];
                }
            }
            Console.WriteLine("Min:" + minnum);
            Console.WriteLine("Max:" + maxnum);


            Console.WriteLine("=======冒泡排序========");
            for (int i = 0; i < array.Length; i++)
            {
                for (int j = 0; j < array.Length - i - 1; j++)
                {
                    var temp = 0;
                    if (array[j] > array[j + 1])
                    {
                        temp = array[j];
                        array[j] = array[j + 1];
                        array[j + 1] = temp;
                    }
                }
            }
            //冒泡排序算法
            for (int i = 0; i < array.Length; i++)
            {
                Console.Write(array[i]+" ");
            }

            Console.WriteLine("\r\n=======快速排序========");
            //快速排序算法

            var list = new List<int> { 11, 3, 24, 5, 0, 2, 4, 6, -1, 101, 101, 5 };

            QuickSort(list, 0, list.Count );

            foreach (var item in list)
            {
                Console.Write(item+" ");
            }
            //二叉树排序
            Console.ReadLine();
        }

        /// <summary>
        /// 快速排序
        /// </summary>
        /// <param name="nums">集合</param>
        /// <param name="left">开始</param>
        /// <param name="right">总数</param>
        private static void QuickSort(List<int> nums, int left, int right)
        {

            if (left < right)
            {

                int i = left;

                int j = right - 1;

                int middle = nums[(left + right) / 2];

                while (true)
                {

                    while (i < right && nums[i] < middle)
                    {
                        i++;
                    }

                    while (j > 0 && nums[j] > middle)
                    {
                        j--;
                    }

                    if (i == j) break;

                    nums[i] = nums[i] + nums[j];

                    nums[j] = nums[i] - nums[j];

                    nums[i] = nums[i] - nums[j];

                    if (nums[i] == nums[j]) j--;

                }

                QuickSort(nums, left, i);

                QuickSort(nums, i + 1, right);

            }
        }



    }

 

posted @ 2015-06-09 21:29  b̶i̶n̶g̶.̶  阅读(173)  评论(0编辑  收藏  举报