class Program
{
static void Main(string[] args)
{
int[] x = {1,5,3,7,2,6,4,8};
List<int> y=x.ToList<int>();
List<int> together = mergeSort(y);
Console.WriteLine();
Console.Write("排序后为:");
together.ForEach((int ele) => { Console.Write(ele+" "); });
Console.WriteLine();
Console.ReadKey();
}
static List<int> mergeSort(List<int> x)
{
x.ForEach((int ele) => { Console.Write(ele + " "); });
Console.WriteLine();
List<int> left = new List<int>();
List<int> right = new List<int>();
List<int> together = new List<int>();
if (x.Count<2)
{
return x;
}
else
{
int middle = x.Count / 2;
for (int i = 0; i < middle;i++ )
{
left.Add(x[i]);
}
for (int i = middle; i < x.Count; i++)
{
right.Add(x[i]);
}
List<int> a = mergeSort(left);
List<int> b = mergeSort(right);
together= merge(a, b);
}
return together;
}
static List<int> merge(List<int> left,List<int> right)
{
List<int> result = new List<int>();
int i=0,j=0;
while(i<left.Count && j<right.Count)
{
if (left[i]<=right[j])
{
result.Add(left[i]);
i++;
}
else
{
result.Add(right[j]);
j++;
}
}
while (i < left.Count)
{
result.Add(left[i]);
i++;
}
while (j < right.Count)
{
result.Add(right[j]);
j++;
}
return result;
}
}
总觉得这么写有点那啥……