九大排序之——选择排序

来源:互联网 发布:灌篮高手的影响力知乎 编辑:程序博客网 时间:2024/06/05 10:00

选择排序:


思想:


首先将给定的序列看成是一个有序序列和一个无序序列,选择排序也就是从给定

序列中选取一个最大的(最小的)元素放到有序序列的对应位置,再从剩余的无序

列中挑选一个次大的(次小的)元素放到有序元素的位置,重复上述操作,直到无

序列为空,排序完成。


选择排序图示:



代码实现:

#include<iostream> using namespace std;void Print(int* arr, size_t n) {for (size_t i = 0; i < n; ++i) {cout << arr[i] << " ";}cout << endl;}//升序template<typename T>struct Greater {bool operator()(T& t1, T& t2) {return t1 > t2;}};//降序template<typename T>struct Less {bool operator()(T& t1, T& t2) {return t1 < t2;}};template<typename T, typename Com = Greater<int>>void SelectSort(T* arr, size_t n) {//对max进行初始化int max = 0;//进行选择排序for (size_t i = 0; i < n - 1; ++i) {max = i;for (size_t j = i; j < n; ++j) {if (Com()(arr[max], arr[j])) max = j;}if (max != i) swap(arr[max], arr[i]);}}

复杂度和稳定性


时间复杂度:O(N^2)与初始序列无关

空间复杂度:O(1)
稳定性:不稳定

原创粉丝点击