注:本博文来自Mars博客园博文,稍有改动。

 

由于快速排序多次因为很小的子文件而调用自身,所以可以在其长度较小时,停止使用快速排序,而使用插入排序:

If (right - left <= M) InsertSort(Item, left, right)

M通常取5-25,实验表明,其速度比M=110%以上 

中间元素法:

  • 3个元素的中间元素作为Partition的依据,而不是Item[right],可以保证不出现最坏情况

结合以上方法,可以提高20%-25%的效率 

SGI STL中,使用的快速排序算法就样的 

算法:

//快速排序改进算法

 1 static const int M = 10;
 2 
 3  
 4 
 5 template <class Item>
 6 
 7 void QSort(Item a[], int left, int right)
 8 
 9 {
10 
11 if (right - left <= M)
12 
13 InsertSort(a, left, right);
14 
15 else
16 
17 {
18 
19 exch(a[(left+right)/2], a[right-1]);
20 
21 compexch(a[left], a[right-1]);
22 
23 compexch(a[left], a[right]);
24 
25 compexch(a[right-1], a[right]);
26 
27 //3个数中,a[left]最小,a[right]最大,所以不需要划分
28 
29 int i = Partition(a, left+1, right-1);
30 
31  
32 
33 QSort(a, left, i-1);
34 
35 QSort(a, i+1, right);
36 
37 }
38 
39 }