首先写了一个类用于计时:
class Time:IDisposable { private DateTime _time; public Time() { _time = DateTime.Now; } public void Dispose() { TimeSpan _tmp=DateTime.Now-_time; Console.WriteLine("耗时(毫秒):" + _tmp.TotalMilliseconds); Console.WriteLine(""); } }
各种排序算法:
//快速排序 public static void QuickShort(int[] iarray,int l,int r) { if (l < r) { int i = l, j = r; int x = iarray[l]; while (i < j) { while (i < j && iarray[j] >= x) j--; if (i < j) { iarray[i] = iarray[j]; i++; } while (i < j && iarray[i] < x) i++; if (i < j) { iarray[j] = iarray[i]; j--; } } iarray[i] = x; QuickShort(iarray,l,i-1); QuickShort(iarray, i + 1, r); } } //冒泡排序 public static void MaoPaoShort(int[] iarray) { for(int i=0;i<iarray.Length;i++) for (int j = 1; j < iarray.Length - i; j++) { if (iarray[j-1] > iarray[j]) { int tmp = iarray[j-1]; iarray[j-1] = iarray[j]; iarray[j] = tmp; } } } //希尔排序 public static void ShellShort(int[] iarray) { for(int gap=iarray.Length/2;gap>0;gap/=2) for(int i=gap;i<iarray.Length;i++) for(int j=i-gap;j>=0&&iarray[j] > iarray[j + gap];j-=gap) { int tmp = iarray[j]; iarray[j] = iarray[j + gap]; iarray[j + gap] = tmp; } } //插入排序 public static void InsertSort(int[] a, int n) { int i, j; for (i = 1; i < n; i++) for (j = i - 1; j >= 0 && a[j] > a[j + 1]; j--) { int tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } }
主函数测试部分:
static void Main(string[] args) { Random rd=new Random(); int[] iarray=new int[100000]; for (int i = 0; i < iarray.Length; i++) { iarray[i] = rd.Next(0,132456); } using (new Time()) { Console.WriteLine("快速排序:"); QuickShort(iarray, 0, iarray.Length - 1); } for (int i = 0; i < iarray.Length; i++) { iarray[i] = rd.Next(0, 132456); } using (new Time()) { Console.WriteLine("希尔排序:"); ShellShort(iarray); } for (int i = 0; i < iarray.Length; i++) { iarray[i] = rd.Next(0, 132456); } using (new Time()) { Console.WriteLine("插入排序:"); InsertSort(iarray,iarray.Length); } for (int i = 0; i < iarray.Length; i++) { iarray[i] = rd.Next(0, 132456); } using (new Time()) { Console.WriteLine("冒泡排序:"); MaoPaoShort(iarray); } //foreach (int k in iarray) // Console.Write(k.ToString() + " "); }
测试结果:
1万个数耗时
10万个数耗时
不同电脑测试结果会有所不同,楼主的机子比较差= =