Created
July 5, 2013 19:10
-
-
Save ser1zw/5936597 to your computer and use it in GitHub Desktop.
C#でクイックソートの練習
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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