您的位置:首页 > 其它

插入排序

2016-01-08 16:31 253 查看
<pre name="code" class="cpp">/*
少量元素排序的有效方法
1、从第二个数据开始于前面的全部数据比较
2、将比较的数据插入到正确的位置
*/
#include<iostream>
using namespace std;
void insert_sort(int a[], int length);
int main()
{
int a[] = {2 ,5 ,8 ,3 ,9,10 ,4 ,6 ,1 ,7 };
int length = sizeof(a) / 4;
insert_sort(a, length);
for (int i = 0; i < length; i++)
{
cout << a[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
void insert_sort(int a[] , int length)
{
for (int i = 1; i < length; i++)
{
for (int j = 0; j < i; j++)
{
if (a[i] < a[j])
{
//插入数据
//将数据放到正确位置,比该数据大的全部后移一位
int temp = a[i];
for (int m = i; m > j; m--)
{
a[m] = a[m - 1];
}
a[j] = temp;

break;
}
}
}
}
/*
外循环是需要比较的数据,内循环从数组的0位开始循环比较
*/
/*时间复杂度:最好O(n) 最坏O(n^2);空间复杂度O(n)*/





                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  插入排序 数据