55.C++冒泡排序和选择排序

选择排序(Selection Sort)和冒泡排序(Bubble Sort)是两种基础的排序算法,虽然效率相对较低,但在学习排序算法的过程中非常有用。

目录

一、冒泡排序

什么是冒泡排序

示例代码

二、选择排序

什么是选择排序

示例代码


一、冒泡排序

什么是冒泡排序

冒泡排序每次都比较相邻的两个元素,如果它们的顺序错误,就交换它们。这样每一轮冒泡会使得一个最大(或最小)的元素"浮"到正确的位置。

所以,如果两个元素相等,我想你是不会再无聊地把他们俩交换一下的;如果两个相等的元素没有相邻,那么即使通过前面的两两交换把两个相邻起来,这时候也不会交换,所以相同元素的前后顺序并没有改变,所以冒泡排序是一种稳定排序算法。

示例代码

cpp 复制代码
#include <iostream>
using namespace std;

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]);
            }
        }
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);

    bubbleSort(arr, n);

    cout << "排序后的数组:";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;

    return 0;
}

二、选择排序

什么是选择排序

选择排序每次都从未排序的部分选择最小(或最大)的元素,然后将其放置在已排序部分的末尾。它的主要思想是不断地选择剩余元素中的最小值,并与当前未排序部分的第一个元素交换。

示例代码

cpp 复制代码
#include <iostream>
using namespace std;

void selectionSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int minIndex = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        if (minIndex != i) {
            swap(arr[i], arr[minIndex]);
        }
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);

    selectionSort(arr, n);

    cout << "排序后的数组:";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;

    return 0;
}
相关推荐
xlp666hub3 小时前
C++ 链表修炼指南
数据结构·c++
xlp666hub10 小时前
Leetcode第七题:用C++解决接雨水问题
c++·leetcode
肆忆_11 小时前
实战复盘:手写 C++ 虚拟机的高性能并行 GC (Thread Pool + Work Stealing)
c++
肆忆_12 小时前
虚函数进阶答疑:把上一篇博客评论区里最容易卡住的问题,一次追到底
c++
saltymilk1 天前
使用 C++ 模拟 ShaderLanguage 的 swizzle
c++·模板元编程
xlp666hub1 天前
Leetcode第五题:用C++解决盛最多水的容器问题
linux·c++·leetcode
得物技术1 天前
搜索 C++ 引擎回归能力建设:从自测到工程化准出|得物技术
c++·后端·测试
xlp666hub2 天前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
会员源码网2 天前
构造函数抛出异常:C++对象部分初始化的陷阱与应对策略
c++
xlp666hub2 天前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode