蓝桥杯省赛无忧 课件42 插入排序

01 插入排序的思想

02 插入排序的实现

03 例题讲解

csharp 复制代码
#include <iostream>
#include <vector>
using namespace std;
void insertionSort(vector<int>& arr) {
    int n = arr.size();
    for (int i = 1; i < n; i++) {
        // 选择arr[i]作为要插入的元素
        int key = arr[i];
        // 将arr[i]与前面的元素比较后插入正确的位置
        int j = i - 1;
        // 将大于key的元素向后移动
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        // 插入key
        arr[j + 1] = key;
    }
}
int main() {
    int n;
    cin >> n;
    vector<int> treasures(n);
    for (int i = 0; i < n; i++) {
        cin >> treasures[i];
    }
    insertionSort(treasures);
    for (int i = 0; i < n; i++) {
        cout << treasures[i] << (i < n - 1 ? " " : "\n");
    }
    return 0;
}
相关推荐
Lris-KK12 小时前
力扣Hot100--94.二叉树的中序遍历、144.二叉树的前序遍历、145.二叉树的后序遍历
python·算法·leetcode
Mr_WangAndy12 小时前
C++设计模式_行为型模式_责任链模式Chain of Responsibility
c++·设计模式·责任链模式·行为型模式
麦麦鸡腿堡12 小时前
Java的动态绑定机制(重要)
java·开发语言·算法
时间之里12 小时前
【c++】:Lambda 表达式介绍和使用
开发语言·c++
zy_destiny12 小时前
【工业场景】用YOLOv8实现抽烟识别
人工智能·python·算法·yolo·机器学习·计算机视觉·目标跟踪
坚持编程的菜鸟12 小时前
LeetCode每日一题——螺旋矩阵
c语言·算法·leetcode·矩阵
汉克老师12 小时前
GESP2025年9月认证C++四级( 第三部分编程题(1)排兵布阵)
c++·算法·gesp4级·gesp四级
(●—●)橘子……13 小时前
记力扣2009:使数组连续的最少操作数 练习理解
数据结构·python·算法·leetcode
GalaxyPokemon13 小时前
LeetCode - 1171.
算法·leetcode·链表
budingxiaomoli13 小时前
算法---双指针一
算法