闲着没事,想思考一下两种排序法的直观对比,写了个小程序,代码如下,分析见后面:
class Program { static DateTime t1, t2; static TimeSpan ts1, ts2,ts3; static int c1 = 0, c2 = 0,c3=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_sort0(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_sort0(a, start + 1); } static void bubble_sort1(int[] a) { int t; for (int j = 1; j <= a.Length - 1; j++) { for (int i = a.Length - 1; i >= j; i--) { c3++; if (a[i - 1] > a[i]) { t = a[i - 1]; a[i - 1] = a[i]; a[i] = t; } } } } static void Main(string[] args) { int[] a, b,c; int length = 2500; 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]; c = new int[a.Length]; a.CopyTo(b, 0); a.CopyTo(c, 0); //bubble_sort0 start t1 = DateTime.Now; bubble_sort0(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); //bubble_sort1 start t1 = DateTime.Now; bubble_sort1(b); t2 = DateTime.Now; ts3 = 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_sort0 spends {ts2.Milliseconds} ms.count={c2}"); Console.WriteLine($"Bubble_sort1 spends {ts3.Milliseconds} ms.count={c3}"); Console.ReadKey(); } }
运行结果如图:
想要看到更悬殊的差距,自行调大“int length =2500;”的值就可以了。
简单地分析:
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次方增加的)
3、bubble_sort0和bubble_sort1是递归与否的差别。可以看出递归会消耗一点时间。事实上,递归也很耗空间。
仅考虑比较多次数,快排完胜。