标签:数字 lse datetime tar ISE 多次 csharp date for
闲着没事,想思考一下两种排序法的直观对比,写了个小程序,代码如下,分析见后面:
class Program { static DateTime t1, t2; static TimeSpan ts1,ts2; static int c1 = 0, c2 = 0; static void quick_sort(int[] a, int start, int end) { int key, i, j, dir = -1; if (end <= start) { return; } i = start; key = a[i]; j = end + 1; while (i < j) { c1++; if (dir == -1) { if (a[--j] < key) { a[i] = a[j]; dir = 1; } } else { if (a[++i] > key) { a[j] = a[i]; dir = -1; } } } a[i] = key; quick_sort(a, start, i - 1); quick_sort(a, i + 1, end); } static void bubble_sort(int[] a, int start) { int t; if(start==a.Length-1) { return; } for (int i = a.Length - 1; i >= start +1; i--) { c2++; if (a[i - 1] > a[i]) { t = a[i - 1]; a[i - 1] = a[i]; a[i] = t; } } bubble_sort(a, start + 1); } static void Main(string[] args) { int[] a,b; int length =100; a = new int[length*3]; //init array for(int index=0,i=1,j=length+1,k= length*2+1; i<=length;i++,j++,k++) { a[index++] = i; a[index++] = j; a[index++] = k; } a.Reverse(); b = new int[a.Length]; a.CopyTo(b, 0); //bubble_sort start t1 = DateTime.Now; bubble_sort(b, 0); t2 = DateTime.Now; ts2 = t2.Subtract(t1); //quick_sort start t1 = DateTime.Now; quick_sort(a, 0, a.Length - 1); t2 = DateTime.Now; ts1 = t2.Subtract(t1); //output array ////Console.WriteLine("Array a:"); ////foreach (var item in a) ////{ //// Console.Write(item + " "); ////} ////Console.WriteLine(); ////Console.ReadKey(); ////Console.WriteLine("Array b:"); ////foreach (var item in b) ////{ //// Console.Write(item + " "); ////} ////Console.WriteLine(); ////Console.ReadKey(); Console.WriteLine($"Quick_sort spends {ts1.Milliseconds} ms.count={c1}"); Console.WriteLine($"Bubble_sort spends {ts2.Milliseconds} ms.count={c2}"); Console.ReadKey(); } }
运行结果如图:
想要看到更悬殊的差距,自行调大“int length =100;”的值就可以了。
简单地分析:
1、冒泡法对n个数排序,第一次比较n-1个,第二次比较n-2个,第三次比较n-3个。。。。以此类推。
2、快排对n个数排序,第一次比较n-1(分界数0,参照数1)个,第二次比较n-3(分界数1,参照数2)个,第三次比较n-7(分界数3,参照数4)个,第四次比较n-15(分界数7,参照数8)。。。。以此类推
(每次比较都会去掉分界点的那个数字和每组中的一个数字,而组数是按2的n次方增加的)
仅考虑比较多次数,快排完胜。
标签:数字 lse datetime tar ISE 多次 csharp date for
原文地址:https://www.cnblogs.com/wanjinliu/p/10969724.html