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;
}
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//通过委托调用方法
SortMethod.Comparison com = new SortMethod.Comparison(Comp);
string[] str = TextBox1.Text.Trim().Split(',');
//进行排序
SortMethod.Sort.BubbleSort(str,com);
//输出
Label1.Text = "";
for (int i = 0; i < str.Length; i++)
{
Label1.Text += str[i].ToString() + ",";
}
}
//比较方法,这里可以自己定义
public bool Comp(object a, object b)
{
return Convert.ToInt32(a) < Convert.ToInt32(b);
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#设计模式 排序算法与委托结合运用 - Python技术站