• C++冒泡排序 (基于函数模板实现)


    冒泡排序是一种简单的排序算法。

     1 #pragma once
     2 #include <iostream>
     3 #include <assert.h>
     4 using std::cout;
     5 using std::endl;
     6 template <typename T> void Swap(T &a, T &b)
     7 {
     8     T temp = a;
     9     a = b;
    10     b = temp;
    11 }
    12 
    13 template <typename T> void Bubble(T a[], unsigned int n)
    14 {
    15     assert(sizeof(a) / sizeof(T) != n);
    16     for (int k = 0; k < n; ++k)
    17         cout << a[k] << "	";
    18     cout << endl;
    19 
    20     int loop = 0;
    21     for (int i = 1; i < n - 1; ++i)
    22     {
    23         bool sorted = true;
    24         cout << "" << i << "次循环" << endl;
    25         for (int j = 1; j < n; ++j)
    26         {
    27             if (a[j] < a[j - 1])
    28             {
    29                 Swap(a[j], a[j - 1]); 
    30                 sorted = false;
    31             }
    32             for (int k = 0; k < n; ++k)
    33                 cout << a[k] << "	";
    34             cout << endl;
    35             loop++;
    36         }
    37         
    38         if (sorted) break;
    39     }
    40     cout << loop << endl;
    41 }
    42 
    43 
    44 int main()
    45 {
    46     double arr1[10] = { 1.2,3,1,9,6,4,5.9,7.1,8,8 };
    47     int len1 = sizeof(arr1)/sizeof(double);
    48     Bubble(arr1, len1);
    49 
    50     int arr2[10] = { 1,3,1,9,6,4,5,7,8,8 };
    51     int len2 = sizeof(arr2) / sizeof(int);
    52     Bubble(arr2, len2);
    53 
    54     system("pause");
    55     return 0;
    56 }
  • 相关阅读:
    Spring Boot 使用 Dev-tool 热部署
    Spring Boot 上传文件
    Spring Boot 目录文件结构
    Spring MVC 文件上传
    Spring MVC 混合使用多种视图技术
    XmlViewResolver 和 ResourceBundleViewResolver
    XML 和 Json
    Excel 和 PDF
    04-树5 Root of AVL Tree (25 分)
    04-树4 是否同一棵二叉搜索树 (25 分)
  • 原文地址:https://www.cnblogs.com/zhaoliankun/p/13020458.html
Copyright © 2020-2023  润新知