C# 实现归并排序

    class Program
    {
        static void Main(string[] args)
        {
            var data2 = new List() { 10, 4, 5, 3, 1, 6, 8, 6, 2 };
            Console.WriteLine("归并排序");
            var sort_data2 = MergeSort(data2);
            sort_data2.ForEach(item => Console.Write(item + " "));

        }


        private static List MergeSort(List data)
        {
            if (data.Count < 2)
                return data;
            int num = data.Count / 2;
            var left = MergeSort(data.Take(num).ToList());
            var right = MergeSort(data.Skip(num).ToList());
            return Merge(left, right);
        }

        private static List Merge(List left, List right)
        {
            int l=0 ,r = 0;
            List newdata = new List();
            while (l < left.Count && r < right.Count)
                newdata.Add(left[l] <= right[r] ? left[l++] : right[r++]);
            newdata.AddRange(left.Skip(l));
            newdata.AddRange(right.Skip(r));
            return newdata;
        }

    }

 

你可能感兴趣的:(C#)