冒泡排序算法
2025-01-28 14:39 钟铧若岩 阅读(5) 评论(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> bubbleSort(std::vector<int> arr) { int n = arr.size(); for (int i = 0; i < n; ++i) { for (int j = 0; j < n - i - 1; ++j) { if (arr[j] > arr[j + 1]) { // 交换元素 int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; printArray(arr); } } cout<<endl; } 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 = bubbleSort(arr); std::cout << "Bubble sorted array: \n"; printArray(bubbleSorted); return 0; }
输出:
Original array:
64 25 12 22 11
25 64 12 22 11
25 12 64 22 11
25 12 22 64 11
25 12 22 11 64
12 25 22 11 64
12 22 25 11 64
12 22 11 25 64
12 11 22 25 64
11 12 22 25 64
Bubble sorted array:
11 12 22 25 64
浙公网安备 33010602011771号