using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Sort
{
///
/// 1.If the list is of length 0 or 1, then it is sorted. Otherwise:
/// 2.Divide the unsorted list into two sublists of about half the size.
/// 3.Sort each sublist recursively by re-applying merge sort.
/// 4.Merge the two sublists back into one sorted list.
///
class MergeSort
{
static void Main(string[] args)
{
int[] data = new int[10] { 1, 3, 6, 5, 4, 9, 0, 2, 8, 7 };
//new int[] { 38, 27, 43, 3, 9, 82, 10 };
MergeSort p=new MergeSort();
p.Write(data);
int[] result = p.Sort(data);
Console.ReadKey();
}
private void Write(int[] data)
{
foreach (int x in data)
{
Console.Write(x + " ");
}
Console.WriteLine();
}
//pseudo code
/*
function mergesort(m)
var list left, right, result
if length(m) ≤ 1
return m
var middle = (min(m) + max(m)) / 2
for each x in m up to middle
add x to left
for each x in m after middle
add x to right
left = mergesort(left)
right = mergesort(right)
result = merge(left, right)
return result
*/
int[] Sort(int[] data)
{
int middle = data.Length / 2;
int[] left=new int[data.Length/2], right=new int[data.Length/2], result=new int[data.Length];
if (data.Length % 2 != 0)
{
right = new int[middle + 1];
}
if (data.Length <= 1)//1 or 0
{
return data;
}
int i = 0,j=0;
foreach (int x in data)
{
if (i < middle)
{
left[i] = x;
i++;
}
else
{
right[j] = x;
j++;
}
}
left = Sort(left);
right = Sort(right);
result = Merge(left, right);
this.Write(result);
return result;
}
/*pseduo code
function merge(a, b)
var list result
var int i, j := 0
while (i < length(a)) and (j < length(b))
if a[i] < b[j]
add a[i] to result
i := i + 1
else
add b[j] to result
j := j + 1
while i < length(a)
add a[i] to result
i := i + 1
while j < length(b)
add b[j] to result
j := j + 1
return result
*/
int[] Merge(int[] a, int[] b)
{
int[] result=new int[a.Length+b.Length];
int i = 0,j=0,k=0;
while(i