zoukankan      html  css  js  c++  java
  • C++ 一起来回忆“冒泡排序”

    例1,输出最大值

     1 #include <iostream>
     2 #include <iomanip>
     3 using namespace std;
     4 int main(void)
     5 {
     6  int a[2][3] = { { 15,34,23 },{ 54,27,65 } };  // 二维数组
     7  int i, j, k;
     8  int row, col;
     9  int max = 0;
    10  for (i = 0; i <= 1; i++)
    11   for (j = 0; j <= 2; j++)
    12   {
    13    cout << setw(4) << a[i][j];
    14    if (j == 2)
    15     cout << endl;
    16   }
    17  cout << " *********************** " << endl;
    18  for (i = 0; i <= 1; i++)
    19   for (j = 0; j <= 2; j++)
    20   {
    21    if (max < a[i][j]) {
    22     max = a[i][j];
    23     row = i+1;
    24     col = j+1;
    25    }
    26   }
    27  cout << "The bigger number is:" << max << endl;
    28  cout << "row=" << row << "," << "col=" << col << endl;
    29  return 0;
    30 }

    结果:  

      15  34  23
      54  27  65
     ***********************
    The bigger number is:65
    row=2,col=3

    ------------------------------------------------------------------------------------

    例2,大小排序(https://baike.baidu.com/item/冒泡排序/4602306?fr=aladdin

     1 #include <iostream>
     2 using namespace std;
     3 template<typename T>
     4 //整数或浮点数皆可使用
     5 void bubble_sort(T arr[], int len)
     6 {
     7     int i, j;  T temp;
     8     for (i = 0; i < len - 1; i++)
     9         for (j = 0; j < len - 1 - i; j++)
    10         if (arr[j] > arr[j + 1])
    11         {
    12             temp = arr[j];
    13             arr[j] = arr[j + 1];
    14             arr[j + 1] = temp;
    15         }
    16 }
    17 int main()
    18 {
    19     int arr[] = { 61, 17, 29, 22, 34, 60, 72, 21, 50, 1, 62 };
    20     int len = (int) sizeof(arr) / sizeof(*arr);
    21     bubble_sort(arr, len);
    22     for (int i = 0; i < len; i++)
    23         cout << arr[i] << ' ';
    24  
    25     cout << endl;
    26  
    27     float arrf[] = { 17.5, 19.1, 0.6, 1.9, 10.5, 12.4, 3.8, 19.7, 1.5, 25.4, 28.6, 4.4, 23.8, 5.4 };
    28     len = (int) sizeof(arrf) / sizeof(*arrf);
    29     bubble_sort(arrf, len);
    30     for (int i = 0; i < len; i++)
    31         cout << arrf[i] << ' ';
    32  
    33     return 0;
    34 }

      

    365个夜晚,我希望做到两天更一篇博客。加油,小白!
  • 相关阅读:
    刷题238. Product of Array Except Self
    刷题236. Lowest Common Ancestor of a Binary Tree
    刷题208. Implement Trie (Prefix Tree)
    A1070
    A1048
    A1050
    A1041
    A1092
    A1084
    n进制转十进制
  • 原文地址:https://www.cnblogs.com/qq2806933146xiaobai/p/12228733.html
Copyright © 2011-2022 走看看