SelectionSort,选择排序,C++实现
1 // g++ selection_sort.cc -Wall -O3 -std=c++11 && ./a.exe 2 3 4 #include <iostream> 5 #include <vector> 6 7 8 static void swap(int &a, int &b) { 9 int temp = a; 10 a = b; 11 b = temp; 12 } 13 14 static size_t GetIndexOfMin(std::vector<int> &arr, size_t begin) { 15 size_t indexOfMin = begin; 16 for (size_t i = begin + 1; i < arr.size(); ++i) { 17 if (arr[i] < arr[indexOfMin]) { 18 indexOfMin = i; 19 } // else nothing 20 } 21 22 return indexOfMin; 23 } 24 25 static void SelectionSort(std::vector<int> &arr) { 26 for (size_t i = 0; i < arr.size(); ++i) { 27 size_t indexOfMin = GetIndexOfMin(arr, i); 28 if (i != indexOfMin) { 29 (void)swap(arr[i], arr[indexOfMin]); 30 } // else no need to swap 31 } 32 } 33 34 int main(int argc, char const *argv[]) { 35 std::vector<int> v { 36 6, 8, 9, 8, 7, 6, 5, 2, 0, -1 37 }; 38 39 (void)SelectionSort(v); 40 for (int i: v) { 41 std::cout << i << "\t"; 42 } 43 std::cout << "\n"; 44 45 return 0; 46 }