在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
周六还要上班,闲来无事,写了一段调用排序算法的类,利用委拖来实现比较,可扩展性比较强。
排序类如下:
代码
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; } } } } } 调用类进行排序
代码
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); }
|
请发表评论