using System;
using System.Collections.Generic;
public static class MergeSortAlgorithm<T>
{
private static void Merge(T[] a, T[] b, T[] c, Comparison<T> comparison)
{
Int32 pa = 0;
Int32 pb = 0;
Int32 pc = 0;
while (pa < a.Length && pb < b.Length)
{
c[pc++] = (comparison(a[pa], b[pb]) <= 0) ? a[pa++] : b[pb++];
}
while (pa < a.Length)
{
c[pc++] = a[pa++];
}
while (pb < b.Length)
{
c[pc++] = b[pb++];
}
}
private static T[] buff;
private static void __MergeSort(T[] a, Int32 left, Int32 right, Comparison<T> comparison)
{
if (left < right)
{
Int32 center = (left + right) / 2;
Int32 p = 0;
Int32 i;
Int32 j = 0;
Int32 k = left;
__MergeSort(a, left, center, comparison);//前半
__MergeSort(a, center + 1, right, comparison);//後半
for (i = left; i <= center; i++)
{
buff[p++] = a[i];
}
while (i <= right && j < p)
{
a[k++] = (comparison(buff[j], a[i]) <= 0) ? buff[j++] : a[i++];
}
while (j < p)
{
a[k++] = buff[j++];
}
}
}
public static void MergeSort(T[] a, Comparison<T> comparison)
{
buff = new T[a.Length];
__MergeSort(a, 0, a.Length - 1, comparison);
}
}
public static class Program
{
static void Main()
{
Random random = new Random();
Int32[] arr = new Int32[1000];
for (Int32 i = 0; i < arr.Length; i++)
{
arr[i] = random.Next() % arr.Length;
}
MergeSortAlgorithm<Int32>.MergeSort(arr, delegate(Int32 x, Int32 y) { return -x.CompareTo(y); });
Array.ForEach(arr, (n) => Console.WriteLine(n));
}
}