插入排序C++实现
来源:互联网 发布:js调试遇到错误中断 编辑:程序博客网 时间:2024/06/12 20:00
有一个已经有序的数据序列,要求在这个已经排好的数据序列中插入一个数,但要求插入后此数据序列仍然有序,这个时候就要用到一种新的排序方法——插入排序法,插入排序的基本操作就是将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据,算法适用于少量数据的排序,时间复杂度为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;}
阅读全文
0 0
- 插入排序C实现
- C实现插入排序
- 插入排序 C实现
- 插入排序C语言实现
- C/C++实现插入排序
- 插入排序的c实现
- 插入排序c语言实现
- 插入排序C语言实现
- 插入排序C语言实现
- 插入排序(C语言实现)
- 插入排序(C实现)
- 插入排序C语言实现
- 插入排序C语言实现
- c语言实现插入排序
- c语言实现插入排序
- linux c 实现插入排序
- 插入排序C语言实现
- C插入排序法实现
- centos6.5搭建PHP环境步骤
- JSX语法
- Bag of Words(BOW)模型
- ubuntu 14.04 安装fcitx以及搜狗拼音输入法
- 多线程
- 插入排序C++实现
- 编程第五十天
- find按照文件大小查找
- 实际应用的css箭头
- 设计模式—工厂模式(五)
- 数据结构知识点整理(思维导图版)
- java 规则引擎
- 【HDU 2795】Billboard
- Android——UI(三):Shader