有一个已经有序的数据序列,要求在这个已经排好的数据序列中插入一个数,但要求插入后此数据序列仍然有序,这个时候就要用到一种新的排序方法——插入排序法,插入排序的基本操作就是将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据,算法适用于少量数据的排序,时间复杂度为O(n^2)。是稳定的排序方法。
待插入的位置 应该是第一个比带插入数值大的元素所在的位置,可以想象一下玩纸牌接完牌整理的时候 ^_^
- 最差时间复杂度: O(n^2)
- 最优时间复杂度: O(n)
- 平均时间复杂度: O(n^2)
- 稳定性: 稳定
#include <iostream>
#include <time.h>
#include <fstream>
#include <vector>
using namespace std;
vector<int> d; //数组
void ReadData(); //读取数据
void InsertSort(vector<int> &a); //选择排序
void printVector(const vector<int> &a); //输出函数
void swap_ele(int *p1, int *p2); //
int main(int argc, char *argv[])
{
clock_t start,end;
start=clock();
double TotalTime;
ReadData();
InsertSort(d);
printVector(d);
end=clock();
TotalTime=(double)(end-start)/CLOCKS_PER_SEC;
cout<<"\n Total Running Time : "<<TotalTime<<endl;
system(("pause"));
return 0;
}
void InsertSort(vector<int> &a) //插入排序
{
int i, j;
for(i=1;i<a.size();i++)
{
for(j=0;j<i;j++)
{
if((a[j]>a[i])) //确定插入位置,即第一个比带插入值大的位置
swap_ele(&a[i],&a[j]); //排序
}
}
}
void swap_ele(int *p1,int *p2)
{
int temp;
temp=*p1;
*p1=*p2;
*p2=temp;
}
void ReadData()
{
extern vector<int> d;
int ele;
fstream InFile("E:/QT/SelectionSort/data.txt");
while (!InFile.eof())
{
InFile>>ele;
d.push_back(ele);
}
d.pop_back();
}
void printVector(const vector<int> &a)
{
for (int i = 0; i < a.size(); i++)
{
cout << a[i] << " ";
}
cout << endl;
}