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