选择排序
如图,每次在黄色的部分选择最小的数,和黄色部分第一个数进行交换,每次都将最小的给选择出来,所以叫选择排序
#include <iostream>
#include "../head_file/template_head.h"
#include <vector>
using namespace std;
void selection_sort()
{
cout << "Selection Sort!!!" << endl;
vector<int> list = { 8,9,1,7,2,3,5,4,6,0,11,9,8 };
selectionSort(list.begin(), list.end());
//selectionSort(list);
cout << "ans: ";
printList(list);
}
template <typename T>
//void selectionSort(const vector<int>& list) {
// selectionSort(list.begin(), list.end());
//}
template <typename Iterator>
void selectionSort(const Iterator& begin, const Iterator& end) {
selectionSort(begin, end, less_<decltype(*begin)>{});
}
template <typename Iterator, typename Comparator>
void selectionSort(const Iterator& begin, const Iterator& end, Comparator lessThan) {
Iterator min_itr = begin;
for (Iterator i = begin; i != end-1; i++) {
for (Iterator j = i; j != end; j++) {
if (lessThan(*j, *min_itr)) {
min_itr = j;
}
}
std::swap(*i, *min_itr);
//printList(begin, end);
}
}