代码改变世界

插入排序

2025-01-28 15:04  钟铧若岩  阅读(7)  评论(0)    收藏  举报
#include <iostream>
using namespace std;


#include <iostream>
#include <vector>
// 打印数组函数
void printArray(const std::vector<int>& arr) {
    for (int num : arr) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
}
// 插入排序函数
std::vector<int> insertionSort(std::vector<int> arr) {
    int n = arr.size();
    for (int i = 1; i < n; ++i) {
        int key = arr[i];
        int j = i - 1;
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            //printArray(arr);
            --j;
        }
        cout<<endl;
        arr[j + 1] = key;
        printArray(arr);
        
    }
    return arr;
}

int main() {
    
    
     std::vector<int> arr = {64, 25, 12, 22, 11};

    std::cout << "Original array: \n";
    printArray(arr);
    std:cout<<endl;

    // 冒泡排序
    std::vector<int> bubbleSorted = insertionSort(arr);
    std::cout << "Bubble sorted array: \n";
    printArray(bubbleSorted);
    return 0;
}

输出:

Original array: 
64 25 12 22 11 


25 64 12 22 11 

12 25 64 22 11 

12 22 25 64 11 

11 12 22 25 64 
Bubble sorted array: 
11 12 22 25 64