zoukankan      html  css  js  c++  java
  • 冒泡排序

    冒泡排序算法的原理如下:
    1.比较相邻的元素。如果第一个比第二个大,就交换他们两个。
    2.对每一对相邻元素做同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
    3.针对所有的元素重复以上的步骤,除了最后一个。
    4.持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。

    C++:

    #include <iostream>
    using namespace std;
    template<typename T>
    //整数或浮点数皆可使用
    void bubble_sort(T arr[], int len)
    {
        int i, j;  T temp;
        for (i = 0; i < len - 1; i++)
            for (j = 0; j < len - 1 - i; j++)
            if (arr[j] > arr[j + 1])
            {
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
    }
    int main()
    {
        int arr[] = { 61, 17, 29, 22, 34, 60, 72, 21, 50, 1, 62 };
        int len = (int) sizeof(arr) / sizeof(*arr);
        bubble_sort(arr, len);
        for (int i = 0; i < len; i++)
            cout << arr[i] << ' ';
     
        cout << endl;
     
        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 };
        len = (int) sizeof(arrf) / sizeof(*arrf);
        bubble_sort(arrf, len);
        for (int i = 0; i < len; i++)
            cout << arrf[i] << ' ';
     
        return 0;
    }
    

    Python

    def bubble_sort(nums):
        for i in range(len(nums) - 1):  # 这个循环负责设置冒泡排序进行的次数
            for j in range(len(nums) - i - 1):  # j为列表下标,第n轮(i轮)确定了最后n-1个数(i个数)不用参与对比
                if nums[j] > nums[j + 1]:
                    nums[j], nums[j + 1] = nums[j + 1], nums[j]
        return nums
     
    print(bubble_sort([45, 32, 8, 33, 12, 22, 19, 97]))
    # 输出:[8, 12, 19, 22, 32, 33, 45, 97]
    
  • 相关阅读:
    自编游戏
    宣言
    Leetcode: 12. Integer to Roman
    Leetcode: 11. Container With Most Water
    Leetcode: 10. Regular Expression Matching
    网络编程:listen函数
    网络编程:connect函数
    Leetcode: 9. Palindrome Number
    Leetcode: 8. String to Integer (atoi)
    Leetcode: 7. Reverse Integer
  • 原文地址:https://www.cnblogs.com/bqwzx/p/11028232.html
Copyright © 2011-2022 走看看