一、选择排序简介
选择排序(Selection sort)是一种简单直观的排序算法。
它的基本思想是:首先在未排序的数列中找到最小(or最大)元素,然后将其存放到数列的起始位置;接着,再从剩余未排序的元素中继续寻找最小(or最大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。
二、 选择排序的时间复杂度和稳定性
选择排序时间复杂度
选择排序的时间复杂度N2)。
假设被排序的数列中有N个数。遍历一趟的时间复杂度是O(N),需要遍历多少次呢?N-1!因此,选择排序的时间复杂度是O(N2)。
选择排序稳定性
选择排序是稳定的算法,它满足稳定算法的定义。
算法稳定性 – 假设在数列中存在a[i]=a[j],若在排序之前,a[i]在a[j]前面;并且排序之后,a[i]仍然在a[j]前面。则这个排序算法是稳定的!
三、C++代码实现
1.实现代码
//Sort.h
#include<vector>
using namespace std;
template <typename T>
bool lessthan(const T &a, const T &b)
{
return a < b;
}
template <typename T>
void exch(T &a, T &b)
{
T temp = a;
a = b;
b = temp;
}
template <typename T>
void show(const vector<T> &a)
{
for (auto tmp : a)
cout << tmp<<" ";
}
template <typename T>
bool isSorted(const vector<T> &a)
{
int cnt = a.size();
for (int i = 0; i < cnt-1; i++)
{
if (a[i] > a[i + 1])
return false;
}
return true;
}
template <typename T>
void read(vector<T> &v, const string s)
{
ifstream data(s); //待读取文件的目录
string line;
while (getline(data, line)) {
stringstream ss; //输入流
ss << line; //向流中传值
if (!ss.eof()) {
int temp;
while (ss >> temp) //提取int数据
v.push_back(temp); //保存到vector
}
}
}
template <typename T>
void SelectionSort(vector<T> &a)
{
int cnt = a.size();
for (int i = 0; i < cnt; i++)
{
int min = i;
for (int j = i + 1; j < cnt; j++)
{
if (!lessthan(a[min], a[j]))
{
min = j;
}
}
exch(a[min], a[i]);
}
}
2.用例代码
#include<iostream>
#include<fstream>
#include<sstream>
#include<algorithm>
#include<string>
#include<vector>
#include<time.h>
#include"Sort.h"
using namespace std;
int main()
{
clock_t start, finish;
double time=0; // CLOCKS_PER_SEC;
vector<int> vec;
read(vec, "4Kints.txt");
cout << vec.size()<<endl;
for (int i = 0; i < 10; i++)
{
start = clock(); //测试程序段花费的时间
SelectionSort(vec);
//InsertionSort(vec);
//ShellSort(vec);
//MergeSort(vec);
//QuickSort(vec);
finish = clock();
time += (double)(finish - start);
cout << isSorted(vec) << endl;
random_shuffle(vec.begin(), vec.end());
}
cout << "运行时间是" << time<<endl;
system("pause");
}