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行)。

  • 相关阅读:
    【杂谈】SpringBoot为啥不用配置启动类
    【API知识】SpringBoot项目中@EnableXXX的原理
    【杂谈】再看生产-消费模式
    【杂谈】Hash表与平衡树
    【杂谈】如何对Redis进行原子操作
    【杂谈】从底层看锁的实现2
    【杂谈】从底层看锁的实现
    HashMap的简易解读
    定时任务、反射、注解
    值得收藏的js原型详解
  • 原文地址:https://www.cnblogs.com/xiaochou/p/13667584.html
Copyright © 2011-2022 走看看