BubbleSort,冒泡排序,C++非递归和递归实现

 1 // g++ bubble_sort.cc -Wall -O3 && ./a.exe
 2 
 3 
 4 #include <iostream>
 5 #include <vector>
 6 
 7 
 8 static void swap(int &a, int &b) {
 9     b = a + b;
10     a = b - a;
11     b = b - a;
12 }
13 
14 static void BubbleSort(std::vector<int> &arr) {
15     for (size_t i = 0; i < arr.size(); ++i) {
16         for (size_t j = 0; j < arr.size() - i - 1; ++j) {
17             if (arr[j] > arr[j + 1]) {
18                 swap(arr[j], arr[j + 1]);
19             } // else nothing
20         }
21     }
22 }
23 
24 int main(int argc, char const *argv[]) {
25     std::vector<int> v {
26         6, 8, 9, 8, 7, 6, 5, 2, 0, -1
27     };
28 
29     (void)BubbleSort(v);
30     for (int i: v) {
31         std::cout << i << "	";
32     }
33     std::cout << "
";
34 
35     return 0;
36 }

    冒泡排序的递归实现如下:

 1 // g++ bubble_sort.cc -Wall -O3 && ./a.exe
 2 
 3 
 4 #include <iostream>
 5 #include <vector>
 6 
 7 
 8 static void swap(int &a, int &b) {
 9     b = a + b;
10     a = b - a;
11     b = b - a;
12 }
13 
14 static void BubbleSortRecursive(std::vector<int> &arr, size_t end) {
15     if (end <= 0) {
16         std::cout << "End procession.
";
17         return;
18     }
19 
20     for (size_t j = 0; j < end; ++j) {
21         if (arr[j] > arr[j + 1]) {
22             swap(arr[j], arr[j + 1]);
23         } // else nothing
24     }
25 
26     return BubbleSortRecursive(arr, end - 1);
27 }
28 
29 int main(int argc, char const *argv[]) {
30     std::vector<int> v {
31         6, 8, 9, 8, 7, 6, 5, 2, 0, -1
32     };
33 
34     (void)BubbleSortRecursive(v, v.size() - 1);
35     for (int i: v) {
36         std::cout << i << "	";
37     }
38     std::cout << "
";
39 
40     return 0;
41 }

    和非递归方式相比,只是修改了:① 终止条件(15-18行);② 将内循环提了出来(20-24行)。

原文地址:https://www.cnblogs.com/xiaochou/p/13667584.html