zd_cugcs

导航

快速排序结合插入排序

继上一篇堆排序之后,用相同的数据结构写了个快速排序和插入排序,当数组的长度较小的时候,可使用插入排序,实现如下:

QuickSort.h

 1 #ifndef __QUICKSORT
 2 #define __QUICKSORT
 3 #include "MySqList.h"
 4 #include "InsertSort.h"
 5 
 6 template <typename Type>
 7 void QuickSort(MySqList<Type>* L, int low, int high)
 8 {
 9     if(high==low)
10         return;
11     else if(high-low < 6)
12         InsertSort(L, low, high);
13     else
14     {
15         int temp = Partition(L, low, high);
16         QuickSort(L, low, temp-1);
17         QuickSort(L, temp+1, high);
18     }
19 }
20 
21 template <typename Type>
22 int Partition(MySqList<Type>* L, int low, int high)
23 {
24     int temp = (low+high)/2;
25     while(low<high)
26     {
27         while(low<high&&L->get(high)>L->get(temp))
28             high--;
29         L->swap(temp, high);
30         temp = high;
31 
32         while(low<high&&L->get(low)<L->get(temp))
33             low++;
34         L->swap(temp, low);
35         temp = low;
36     }
37     return temp;
38 }
39 
40 #endif
View Code

InsertSort.h

 1 #ifndef __INSERTSORT
 2 #define __INSERTSORT
 3 #include "MySqList.h"
 4 template <typename Type>
 5 void InsertSort(MySqList<Type>* L, int low, int high)
 6 {
 7     if(!L)
 8         return;
 9     if(high==low)
10         return;
11     int min_id;
12     for(int i = low; i<=high; i++)
13     {
14         min_id = i;
15         for(int j=i+1; j<=high; j++)
16         {
17             if(L->get(j)<L->get(min_id))
18                 min_id = j;
19         }
20         L->swap(i,min_id);
21     }
22 }
23 #endif
View Code

main.cpp

 1 #include "MySqList.cpp"
 2 #include "InsertSort.h"
 3 #include "QuickSort.h"
 4 int main()
 5 {
 6     int b[9]={1,6,7,8,9,256,3,4,5}; 
 7     int len = sizeof(b)/sizeof(int);
 8     MySqList<int > *L = new MySqList<int>(len,b);
 9         QuickSort(ls, 0, ls->Len()-1);
10 }
View Code

当数组长度小于等于5时,用插入排序。

快速排序的中间值选择方法可以改进。希望对大家有用。

posted on 2014-06-04 10:15  zd_cugcs  阅读(406)  评论(0编辑  收藏  举报