快速排序

一个简单的快速排序实现。其中,对比的节点为第一个结点。

 1 #include
 2 #include
 3 #include
 4 #define VectorMax 100
 5 using namespace std;
 6 int vector[VectorMax];        /* * * sort vec * length is vec's length * flag == 0, increase; * flag == 1, decrease * */
 7 void myqsort(int *vec, int length);
 8 void print(int *vec, int length);
 9 int main()
10 {
11     srand(time(NULL));
12     for (int i = 0; i < VectorMax; i++)
13         vector[i] = rand() % 100;
14     myqsort(vector, VectorMax);
15     print(vector, VectorMax);
16     return 0;
17 }
18 /*sort vec[begin, end) */
19 
20 void subSort(int *vec, int begin, int end)
21 {
22     int Tag = vec[begin];
23     int Begin = begin;
24     int End = end - 1;
25     while (Begin < End) {
26         while (vec[End] > Tag && Begin < End)
27             End--;
28         vec[Begin] = Begin < End ? vec[End] : vec[Begin];
29         while (vec[Begin] <= Tag && Begin < End)
30             Begin++;
31         vec[End] = Begin < End ? vec[Begin] : vec[End];
32     }
33     vec[Begin] = Tag;
34     if (Begin - begin > 1)
35         subSort(vec, begin, Begin);
36     if (end - Begin > 1)
37         subSort(vec, Begin + 1, end);
38 }
39 
40 void myqsort(int *vec, int length)
41 {
42     subSort(vec, 0, length);
43 } 
44 void print(int *vec, int length)
45 {
46     for (int i = 0; i < length; i++)
47         cout << vec[i] << " ";
48     cout << endl;
49 }

 

你可能感兴趣的:(快速排序)