閑着沒事,想思考一下兩種排序法的直觀對比,寫了個小程序,代碼如下,分析見后面:
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是遞歸與否的差別。可以看出遞歸會消耗一點時間。事實上,遞歸也很耗空間。
僅考慮比較多次數,快排完勝。