Skip to content

Instantly share code, notes, and snippets.

@ser1zw
Created July 5, 2013 19:10
Show Gist options
  • Save ser1zw/5936597 to your computer and use it in GitHub Desktop.
Save ser1zw/5936597 to your computer and use it in GitHub Desktop.
C#でクイックソートの練習
using System;
namespace QuickSort
{
class MainClass
{
private static void quickSortInternal<Type>(Type[] array, int left, int right, Func<Type, Type, int> compare)
{
if (left >= right)
{
return;
}
var i = left;
var j = right;
var pivot = array[i];
while (true)
{
while (i < right && compare(pivot, array[i]) < 0)
{
i++;
}
while (j >= left && compare(pivot, array[j]) > 0)
{
j--;
}
if (i >= j)
{
break;
}
var tmp = array[i];
array[i] = array[j];
array[j] = tmp;
i++;
j--;
}
quickSortInternal(array, left, i - 1, compare);
quickSortInternal(array, j + 1, right, compare);
}
public static Type[] QuickSort<Type>(Type[] array, Func<Type, Type, int> compare)
{
var buff = new Type[array.Length];
array.CopyTo(buff, 0);
quickSortInternal(buff, 0, buff.Length - 1, compare);
return buff;
}
public static void Main(string[] args)
{
int[] data = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9 };
Console.WriteLine("Data: {0}", String.Join(" ", data));
var asc = QuickSort(data, (a, b) => (a == b) ? 0 : (a < b) ? 1 : -1);
Console.WriteLine("Asc: {0}", String.Join(" ", asc));
var desc = QuickSort(data, (a, b) => (a == b) ? 0 : (a > b) ? 1 : -1);
Console.WriteLine("Desc: {0}", String.Join(" ", desc));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment