冒泡排序

算法思想:

代码实现(C++):

#include<iostream>
#include<vector>
#include<stdlib.h>
using namespace std;

void BubbleSort(vector<int>& nums) {
    int sz = nums.size();
    for (int i = 0 ; i < sz-1 ; i++) {
        for (int j = 0 ; j < sz - 1 - i; j++) {
            if (nums[j] > nums[j+1])
                swap(nums[j], nums[j+1]);
        }
    }
}

int main() {
    vector<int> nums;
    for (int i = 0; i < 10; i++) {
        nums.push_back(rand() % 100);
    }
    cout << "排序前: ";
    for (int i = 0; i < 10; i++) {
        cout << nums[i] << " ";
    }
    cout << endl;
    BubbleSort(nums);
    cout << "排序后: ";
    for (int i = 0; i < 10; i++) {
        cout << nums[i] << " ";
    }
    return 0;
}

输出结果:

Last updated