代码改变世界

C# 泛型冒泡排序

2012-12-15 15:15  清潭荷韵  阅读(1023)  评论(0编辑  收藏  举报

服务代码:

  

 1     internal static class BubbleSort
 2     {
 3         internal static void Excute<T>(T[] arr, IComparer<T> comparer)
 4         {
 5             for (int i = 0; i < arr.Length - 1; i++)
 6             {
 7                 for (int j = i + 1; j < arr.Length; j++)
 8                 {
 9                     if (comparer.Compare(arr[i], arr[j]) > 0)
10                     {
11                         var temp = arr[i];
12                         arr[i] = arr[j];
13                         arr[j] = temp;
14                     }
15                 }
16             }
17         }
18     }

客户代码:

 1     internal class Program
 2     {
 3         static void Main(string[] args)
 4         {  
 5             int[] intArr = new int[] { 4, 6, 1, 7, 2 };
 6             BubbleSort.Excute<int>(intArr, new IntComparer());
 7             foreach (int item in intArr)
 8                 Console.WriteLine(item.ToString() + ",");
 9         }
10 
11     }
12 
13     internal class IntComparer : IComparer<int>
14     {
15         public int Compare(int x, int y)
16         {
17             if (x > y)
18                 return 1;
19             else if (x == y)
20                 return 0;
21             else
22                 return -1;
23         }
24     }