快速排序(基于顺序容器vector;基于数组array)
快速排序(基于顺序容器vector;基于数组array)
·
代码1:基于顺序容器vector
1 /*
2 * FILE: quick_sort_vector.cpp
3 * ---------------------------
4 * DATE: 20170818
5 * 快速排序,基于顺序容器vector
6 */
7
8 #include <iostream>
9 #include <vector>
10
11 /*
12 * Implementation notes: partition
13 * -------------------------------
14 * This function rearrange the elements of the vector
15 */
16
17 int partition(std::vector<int> &v, int begin, int end)
18 {
19 int pivot = v[begin];
20 int left = begin + 1;
21 int right = end;
22 while(true)
23 {
24 while(left < right && v[right] >= pivot)
25 right--;
26 while(left < right && v[left] < pivot)
27 left++;
28 if(left == right)
29 break;
30 std::swap(v[left], v[right]);
31 }
32 if(v[left] >= pivot)
33 return begin;
34 v[begin] = v[left];
35 v[left] = pivot;
36 return left;
37 }
38
39 /*
40 * Implementation notes: quickSort
41 * -------------------------------
42 * This function sorts the elements in the vector between
43 * index position begin and end, inclusive
44 */
45 void quickSort(std::vector<int> &v, int begin, int end)
46 {
47 if(begin >= end)
48 return;
49 int boundary = partition(v, begin, end);
50 quickSort(v, begin, boundary - 1);
51 quickSort(v, boundary + 1, end);
52 }
53
54 /*
55 * Implemention notes: sort
56 * ------------------------
57 * This function sorts the elements of the vector into
58 * increasing numerical order using the QuickSort algorithm
59 */
60 void sort(std::vector<int> &v)
61 {
62 quickSort(v, 0, v.size() - 1);
63 }
64
65 void display(std::vector<int> &v)
66 {
67 for(std::vector<int>::iterator iter= v.begin(); iter != v.end(); iter++ )
68 std::cout<< *iter << " ";
69 std::cout<< std::endl;
70 }
71
72 int main(int argc, char *argv[])
73 {
74 int a[] ={3,4,2,1,7,5,8,9,0,6};
75 std::vector<int> vec(a, a+10);
76 sort(vec);
77 display(vec);
78 return 0;
79 }
代码2:基于数组array
1 /*
2 * FILE: quick_sort.cpp
3 * --------------------
4 * DATE: 20170818
5 *
6 *
7 */
8
9 #include <iostream>
10
11 void quickSort(int a[], int begin, int end);
12
13 int main(int argc, char *argv[])
14 {
15 int a[] = {3,4,2,1,7,5,8,9,0,6};
16 int length = sizeof(a) / sizeof(int);
17
18 quickSort(a, 0, length-1); // 快速排序
19
20 for(int i = 0; i < length; i++)
21 std::cout<< a[i] << " ";
22 std::cout<< std::endl;
23 return 0;
24 }
25
26 /* 快速排序 */
27 void quickSort(int a[], int begin, int end)
28 {
29 if(begin >= end)
30 return;
31 int left = begin, right = end;
32 int pivot_value = a[left];
33 while(left < right)
34 {
35 if(a[left+1] < pivot_value)
36 {
37 a[left] = a[left+1];
38 left++;
39 }
40 else if(a[left+1] >= pivot_value)
41 {
42 std::swap(a[left+1], a[right]); // std::swap()
43 right--;
44 }
45 }
46 a[left] = pivot_value;
47 quickSort(a, begin, left-1); // 递归
48 quickSort(a, left+1, end);
49 }
更多推荐
已为社区贡献1条内容
所有评论(0)