用委托定义的冒泡排序法

1.排序的类

public class BubbleSorter {

static public void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparison) {
bool swapped = true;
do {
swapped = false;
for (int i = 0; i < sortArray.Count - 1; i++) {
if (comparison(sortArray[i + 1], sortArray[i])) {
T tmp = sortArray[i];
sortArray[i] = sortArray[i + 1];
sortArray[i + 1] = tmp;
swapped = true;
}
}
} while (swapped);
}
}

2.定义一个数据比较的方法

public static bool CompareValue(int x, int y)
{
return x < y;
}

3.调用方法排序

IList<int> arraySort = new int[] { 7, 4, 3, 5, 2, 7, 9, 4, 5 };
BubbleSorter.Sort(arraySort, CompareValue);
for (int i = 0; i < arraySort.Count; i++) {
Console.WriteLine("{0}", arraySort[i]);
}
Console.ReadLine();

原文地址:https://www.cnblogs.com/zhang123/p/4261768.html