|
using System;
using System.Text;
public class Test
{
public delegate bool Compare<T>(T rhs, T lhs);
public static void Main()
{
Random r = new Random();
int[] stuff = new int[10];
for (int i = 0; i < stuff.Length; i++)
stuff[i] = r.Next(10);
QuickSort(ref stuff, delegate(int rhs, int lhs){return rhs <= lhs; });
Console.WriteLine(PrintArray(stuff, 0, stuff.Length));
}
public static void QuickSort<T>(ref T[] values, Compare<T> comp)
{
QuickSortRecurse(ref values, 0, values.Length, comp);
}
public static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
public static string PrintArray<T>(T[] values, int start, int end)
{
StringBuilder builder = new StringBuilder();
for (int i = start; i < end; i++)
{
builder.Append(values[i].ToString());
builder.Append(" ");
}
return builder.ToString();
}
public static void QuickSortRecurse<T>(ref T[] values, int start, int end, Compare<T> comp)
{
if ((end - start) < 2) return;
if (((end - start) == 2))
{
if (!comp(values[start], values[end - 1]))
{
Swap(ref values[start], ref values[end-1]);
}
return;
}
int stop = end - 1;
int i = start + 1;
while (i < stop)
{
while (!comp(values[start], values[i]) && i < stop) i++;
while (comp(values[start], values[stop]) && stop >= i) stop--;
if (i < stop)
{
Swap(ref values[i], ref values[stop]);
}
}
if (start < stop)
{
Swap(ref values[start], ref values[stop]);
}
if (start < stop-1)
QuickSortRecurse(ref values, start, stop, comp);
if (stop+1 < end)
QuickSortRecurse(ref values, stop + 1, end, comp);
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.