体验百度文心一言AI模型生成选择排序C++版

以下是C++实现的选择排序代码:

#include <iostream>
#include <vector>

using namespace std;

void selectionSort(vector<int>& arr) {
    
    
    int n = arr.size();
    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() {
    
    
    vector<int> arr = {
    
    5, 3, 8, 6, 2, 7, 1, 4};
    selectionSort(arr);
    for (int i = 0; i < arr.size(); i++) {
    
    
        cout << arr[i] << " ";
    }
    cout << endl;
    return 0;
}
  • 在这个代码中,selectionSort函数使用了两个循环来遍历整个数组。外层循环从第一个元素开始,到倒数第二个元素结束,内层循环从当前位置的下一个元素开始,到最后一个元素结束。内层循环的目的是找到未排序部分中的最小元素,然后将其与当前位置的元素交换。最后,main函数定义了一个整型向量arr,并调用selectionSort函数对其进行排序,然后输出排序后的结果。
C:\Users\Administrator\CLionProjects\untitled1\cmake-build-debug\untitled1.exe
1 2 3 4 5 6 7 8

Process finished with exit code 0

开发工具:百度文心一言
CLion集成开发环境

猜你喜欢

转载自blog.csdn.net/m0_38127487/article/details/132205789