排序算法(一):直接插入排序
2015-11-05 21:02
260 查看
ps:虽然是转载的,但是代码绝对自己重新写过的。
基本思想:
将一个记录插入到已排序好的有序表中,从而得到一个新,记录数增1的有序表。即:先将序列的第1个记录看成是一个有序的子序列,然后从第2个记录逐个进行插入,直至整个序列有序为止。
![](http://my.csdn.net/uploads/201207/17/1342520948_8667.jpg)
算法的实现:
#include <iostream>
using namespace std;
void Print(int a[], int n)
{
for (int i = 0;i < n;i++)
{
cout << a[i] << " ";
}
cout << endl;
}
void InsertSort(int a[], int n)
{
for (int i = 1;i < n;i++)
{
cout << i << " start:" << endl;
if (a[i - 1] > a[i])
{
int tmp = a[i];
int p = i - 1;
a[i] = a[i - 1];
while (p > 0 && a[p - 1] > tmp)
{
a[p] = a[p - 1];
p--;
Print(a, n);
}
a[p] = tmp;
Print(a, n);
}
cout << "end with ";
Print(a, n);
}
}
int main()
{
int a[] = { 3,9,6,5,7,2,4,10,8,1 };
InsertSort(a, 10);
system("pause");
}
效率:
时间复杂度:O(n^2).
其他的插入排序有二分插入排序,2-路插入排序。
个人理解:
最简单的排序方法,一定要注意边界。
基本思想:
将一个记录插入到已排序好的有序表中,从而得到一个新,记录数增1的有序表。即:先将序列的第1个记录看成是一个有序的子序列,然后从第2个记录逐个进行插入,直至整个序列有序为止。
![](http://my.csdn.net/uploads/201207/17/1342520948_8667.jpg)
算法的实现:
#include <iostream>
using namespace std;
void Print(int a[], int n)
{
for (int i = 0;i < n;i++)
{
cout << a[i] << " ";
}
cout << endl;
}
void InsertSort(int a[], int n)
{
for (int i = 1;i < n;i++)
{
cout << i << " start:" << endl;
if (a[i - 1] > a[i])
{
int tmp = a[i];
int p = i - 1;
a[i] = a[i - 1];
while (p > 0 && a[p - 1] > tmp)
{
a[p] = a[p - 1];
p--;
Print(a, n);
}
a[p] = tmp;
Print(a, n);
}
cout << "end with ";
Print(a, n);
}
}
int main()
{
int a[] = { 3,9,6,5,7,2,4,10,8,1 };
InsertSort(a, 10);
system("pause");
}
效率:
时间复杂度:O(n^2).
其他的插入排序有二分插入排序,2-路插入排序。
个人理解:
最简单的排序方法,一定要注意边界。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 在命令行用 sort 进行排序
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- 动易2006序列号破解算法公布
- 文件遍历排序函数
- C#选择排序法实例分析
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- C#实现Datatable排序的方法
- Lua教程(二):C++和Lua相互传递数据示例
- 超大数据量存储常用数据库分表分库算法总结
- SQLSERVER的排序问题结果不是想要的
- Windows Powershell排序和分组管道结果
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析