1
1
#include < iostream>
2
+ #define Cutoff 100
2
3
using namespace std ;
3
4
4
5
/* *
@@ -52,24 +53,70 @@ void Insertion_Sort(int *a , int len){
52
53
}
53
54
54
55
/* *
55
- *希尔排序
56
+ *希尔排序(特殊插入排序)
56
57
*/
57
58
void Sell_Sort (int *a , int len){
58
59
int Sedgewick[] = {929 , 505 , 209 , 109 , 41 , 19 , 5 , 1 , 0 };// 增量序列
59
- int i , n;
60
- for (i = 0 ;Sedgewick[i ] > len ; i ++){}
60
+ int k , n , i ;
61
+ for (k = 0 ;Sedgewick[k ] > len ; k ++){}
61
62
62
- for (int j = i ; j <= 9 ;j ++ ){
63
- for (int m = j ;m < len;m ++){
64
- int temp = a[m ];
65
- for (n = m;n > 0 && a[n - Sedgewick[j]] > temp ;n += Sedgewick[j] ){
66
- a[n ] = a[n - Sedgewick[j] ];
63
+ for (int D = Sedgewick[k] ; D > 0 ; D = Sedgewick[++k] ){
64
+ for (int j = D;j < len ;j ++){
65
+ int temp = a[j ];
66
+ for (i = j ; i > 0 && a[i- 1 ] > temp;i -- ){
67
+ a[i ] = a[i- 1 ];
67
68
}
68
- a[n ] = temp;
69
+ a[i ] = temp;
69
70
}
70
71
}
71
72
}
72
73
74
+ /* *
75
+ * 快速排序
76
+ * best pivot中分 T=O(NlogN)
77
+ * worst pivot[0] T=O(N^2)
78
+ */
79
+ void Swap (int *a , int left , int right){
80
+ int temp = a[left];
81
+ a[left] = a[right];
82
+ a[right] = temp;
83
+ }
84
+ int Median3 (int *a , int left , int right){
85
+ int median = (left +right)/2 ;
86
+ if (a[median] < a[left])
87
+ Swap (a , left , median);
88
+ if (a[right] < a[left])
89
+ Swap (a , left , right);
90
+ if (a[median] > a[right])
91
+ Swap (a , median , right);
92
+ Swap (a , median , right-1 );
93
+ return a[right -1 ];
94
+ }
95
+ void Quick_Sort (int *a , int left , int right){
96
+ if (Cutoff < right -left){
97
+ int pivot = Median3 (a , left , right);
98
+ int Low = left , High = right -1 ;
99
+ for (;;){
100
+ while (a[++Low] < pivot);
101
+ while (pivot < a[--High]);
102
+ if (High < Low)
103
+ break ;
104
+ else
105
+ Swap (a , Low , High);
106
+ }
107
+
108
+ Swap (a , Low , right - 1 );
109
+ Quick_Sort (a , left , Low-1 );
110
+ Quick_Sort (a , Low + 1 , right);
111
+ }else {
112
+ Insertion_Sort (a + left , right -left + 1 );
113
+ }
114
+
115
+ }
116
+ void QSort (int *a , int len){
117
+ Quick_Sort (a , 0 , len -1 );
118
+ }
119
+
73
120
void printArray (int *a , int len){
74
121
for (int i = 0 ;i < len ;i ++){
75
122
cout << a[i] <<" " ;
@@ -79,13 +126,16 @@ void printArray(int *a , int len){
79
126
80
127
int main (){
81
128
int a[] = {5 , 2 , 8 ,1 ,9 , 0 , 4 ,3 ,7 ,6 };
82
- Bubble_Sort (a , 10 );
83
- printArray (a , 10 );
129
+ // Bubble_Sort(a , 10);
130
+ // printArray(a , 10);
84
131
85
- Insertion_Sort (a , 10 );
86
- printArray (a , 10 );
132
+ // Insertion_Sort(a , 10);
133
+ // printArray(a , 10);
87
134
88
135
Sell_Sort (a , 10 );
89
136
printArray (a , 10 );
137
+
138
+ // QSort(a , 10);
139
+ // printArray(a , 10);
90
140
return 0 ;
91
141
}
0 commit comments