C#设计模式:排序算法与委托结合运用
2010-09-30 22:35:49 来源:WEB开发网写了一段调用排序算法的类,利用委拖来实现比较,可扩展性比较强。
排序类如下:
using System;
using System.Collections.Generic;
using System.Text;
namespace SortMethod
{
//主要用来调用比较两个对象的方法
public delegate bool Comparison(object a,object b);
public class Sort
{
/// <summary>
/// 冒泡排序算法
/// </summary>
/// <param name="s"></param>
/// <param name="cp"></param>
public static void BubbleSort(object[] list, Comparison cp)
{
for (int i = 0; i < list.Length; i++)
{
for (int j = i + 1; j < list.Length; j++)
{
if (cp(list[i], list[j]))
{
object rs = list[i];
list[i] = list[j];
list[j] = rs;
}
}
}
}
/// <summary>
/// 选择排序算法
/// </summary>
/// <param name="s"></param>
/// <param name="cp"></param>
public static void SelectSort(object[] list, Comparison cp)
{
int min;
for (int i = 0; i < list.Length; i++)
{
min = i;
for (int j = i + 1; j < list.Length; j++)
{
if (cp(list[min], list[j]))
{
min = j;
}
}
object rs = list[i];
list[i] = list[min];
list[min] = rs;
}
}
/// <summary>
/// 插入排序算法
/// </summary>
/// <param name="s"></param>
/// <param name="cp"></param>
public static void InsertSort(object[] list, Comparison cp)
{
for (int i = 1; i < list.Length; i++)
{
object t = list[i];
int j = i;
while ((j > 0) && cp(t, list[j - 1]))
{
list[j] = list[j - 1];
--j;
}
list[j] = t;
}
}
/// <summary>
/// 希尔排序算法
/// </summary>
/// <param name="s"></param>
/// <param name="cp"></param>
public static void ShellSort(object[] list, Comparison cp)
{
int inc;
for (inc = 1; inc <= list.Length / 9; inc = 3 * inc + 1) ;
for (; inc > 0; inc /= 3)
{
for (int i = inc + 1; i <= list.Length; i += inc)
{
object t = list[i - 1];
int j = i;
while ((j > inc) && cp(t,list[j - inc - 1]))
{
list[j - 1] = list[j - inc - 1];
j -= inc;
}
list[j - 1] = t;
}
}
}
}
}
更多精彩
赞助商链接