1. 程式人生 > >c#泛型氣泡排序法

c#泛型氣泡排序法

public delegate bool Contrast<T>(T t1, T t2);
public static void Sequence<T>(T[] items, Contrast<T> contrast)
{
	for (int i = 0; i < items.Length; i++)
	{
		for (int j = i + 1; j < items.Length; j++)
		{
			if (contrast(items[i], items[j]))
			{
				var temp = items[i];
				items[i] = items[j];
				items[j] = (T)temp;
			}
		}
	}
}

//呼叫方法  
string[] arr = { "w", "s", "t", "a", "9", "e" ,"6"};  
Sequence(arr, (a, b) => a.CompareTo(b) > 0);//順序  
//Sequence(arr, (a, b) => a.CompareTo(b) < 0);//倒序  
Console.WriteLine(string.Join(",", arr));
//Result:6,9,a,e,s,t,w

int[] arr2 = { 4, 1, 66, 3, 0, 42, 87 };  
Sequence(arr2, (a, b) => a > b);
Console.WriteLine(string.Join(",", arr2));
//Result:0,1,3,4,42,66,87