namespace SortProject{ ////// 统一排序接口 /// ///public interface ISort where TElement : IComparable { TElement[] Sorting(); } /// /// 冒泡排序法 /// ///public class BubbleSort : ISort where TElement : IComparable { private TElement[] _dataArray; public BubbleSort(TElement[] dataArray) { _dataArray = dataArray; } public BubbleSort(List dataArray) { _dataArray = dataArray.ToArray(); } public BubbleSort(IEnumerable dataArray) { _dataArray = dataArray.ToArray(); } public TElement[] Sorting() { int lenght = _dataArray.Length; bool flag = false; //TElement temp; for (int i = 0; i < lenght && flag == false;i++) { flag = true; for (int j = 0; j < lenght - i - 1; j++) { if (_dataArray[j].CompareTo(_dataArray[j + 1]) > 0) { SortPublicFunction.Swap (ref _dataArray[j], ref _dataArray[j + 1]); //temp = _dataArray.ElementAt(j + 1); //_dataArray[j + 1] = _dataArray[j]; //_dataArray[j] = temp; flag = false; } } } return _dataArray; } } /// /// 快速排序法 /// ///public class QuickSort : ISort where TElement : IComparable { private TElement[] _dataArray; public QuickSort(TElement[] dataArray) { _dataArray = dataArray; } public QuickSort(List dataArray) { _dataArray = dataArray.ToArray(); } public QuickSort(IEnumerable dataArray) { _dataArray = dataArray.ToArray(); } public TElement[] Sorting() { QuickSorting(_dataArray, 0, _dataArray.Length - 1); return _dataArray; } private void QuickSorting(TElement[] array, int s, int t) { int i, j; if (s < t) { i = s; j = t + 1; while (true) { do i++; while (!(array[s].CompareTo(array[i]) <= 0 || i == t)); do j--; while (!(array[s].CompareTo(array[j]) >= 0 || j == s)); if (i < j) { SortPublicFunction.Swap (ref array[i], ref array[j]); } else { break; } } SortPublicFunction.Swap (ref array[s], ref array[j]); QuickSorting(array, s, j - 1); QuickSorting(array, j + 1, t); } } }}//测试程序 static void Main(string[] args) { int[] da = new int[] { 22, 15, 11, 52, 27, 19, 29, 62, 18 }; Sort (da); float[] da1 = new float[] { 0.98f, 243.98f, 29.0f, 0.87f, 76.87f, 4.19f, 23.29f, 0.62f, 18.98f }; Sort (da1); char[] da2 = new char[] { '2', 'z', 'd', '3', '7', 'u', '8', 'c', 'a' }; Sort (da2); string[] da3 = new string[] { "fef", "15", "1sdf", "asfr5", "59fjk", "d0ei", "0dex", "", "asdf_" }; Sort (da3); List da4 = new List () { 15, 6, 9 }; Sort (da4.ToArray()); Console.WriteLine(); Console.ReadKey(); } private static void Sort (T[] array) where T : IComparable { //ISort temp = new BubbleSort (array); ISort temp = new QuickSort (array); T[] da1 = temp.Sorting(); foreach (T item in da1) { Console.Write("{0} ", item); } Console.WriteLine(); }//cmd测试结果PS C:\Users\××××××> AlgorithmsTest.exe11 15 18 19 22 27 29 52 620.62 0.87 0.98 4.19 18.98 23.29 29 76.87 243.982 3 7 8 a c d u z 0dex 15 1sdf 59fjk asdf_ asfr5 d0ei fef6 9 15