zoukankan      html  css  js  c++  java
  • 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行)。

  • 相关阅读:
    《大道至简》读后感
    周报告
    关于大脑休息之睡觉与冥想方式对比
    大数据之实验6
    学习进度(16)
    软件工程—个人课程总结
    学习进度(15)
    人月神话阅读笔记03
    学习进度(14)
    软件工程—个人作业(8)
  • 原文地址:https://www.cnblogs.com/xiaochou/p/13667584.html
Copyright © 2011-2022 走看看