选择排序(c++练习题)
#include #include #include #include
//std::vector test_array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 };
std::vector test_array = { 13,12,14,19,11,8,9,7,5,6,3,4,2,1 };
// 打印vector内容 void printVector(const std::string prefix, const std::vector& vi) { std::cout << prefix; for (auto i : vi) { std::cout << " " << i; } std::cout << std::endl; }
// 选择排序 void selectSort(std::vector& vi) { // 需要进行 n-1 轮 for (int i = 0; i < vi.size() - 1; ++i) { // 找到此轮的最小值下标 int min_index = i; for (int j = i + 1; j < vi.size(); ++j) { if (vi[j] < vi[min_index]) { min_index = j; } }
std::swap(vi[i], vi[min_index]); } }
int main() { // 乱排有序vector auto rng = std::default_random_engine{}; std::shuffle(std::begin(test_array), std::end(test_array), rng);
// 排序前 printVector("before:", test_array);
// 排序 selectSort(test_array);
// 排序后 printVector("after:", test_array);
return 0; }