一、插入排序简介
直接插入排序(Straight Insertion Sort)的基本思想是:把n个待排序的元素看成为一个有序表和一个无序表。开始时有序表中只包含1个元素,无序表中包含有n-1个元素,排序过程中每次从无序表中取出第一个元素,将它插入到有序表中的适当位置,使之成为新的有序表,重复n-1次可完成排序过程。
二、插入排序的时间复杂度和稳定性
插入排序时间复杂度
直接插入排序的时间复杂度是O(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 InsertionSort(vector<T> &a)
{
int cnt = a.size();
for (int i = 1; i < cnt; i++)
{
for (int j = i; j >0&&lessthan(a[j], a[j-1]); j--)
{
exch(a[j], a[j - 1]);
}
}
}
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");
}