温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

插入排序基础实现

发布时间:2020-06-14 05:08:26 来源:网络 阅读:146 作者:zheng_feng 栏目:编程语言

插入排序是将插入数据与前面的排好序的数据比较然后将数据插入到指定位置时间复杂度为O(N^2)

大概排序流程为将一数组,首先取第二个数据向第一个数据插入排序,一直到第n个向n-1个数组插入排序

#include<iostream>

using namespace std;


void InsertSort(int *a, int length)

{

if (a == NULL || length < +0)

{

return;

}

for(int i = 1; i < length; i++)

{

int index = i;

int tmp = a[i];

while (index)

{

if (tmp < a[index-1])   //插入数据和前面的数据比较,并将大的向后移动

{

a[index] = a[index - 1];

}

else

{

break;

}

--index;

}

if (tmp<a[index])    //将插入的数据放到数组合适的位置

{

a[index] = tmp;

}

}

}

void Test()

{

int a[] = { 3, 6, 2, 8, 1, 5, 9, 4, 7, 0 };

InsertSort(a, 10);

for (int i = 0; i < sizeof(a) / sizeof(a[0])-1; i++)

{

cout << a[i] << " ";

}

cout << endl;

}

int main()

{

Test();

return 0;

}  


附件:http://down.51cto.com/data/2367551
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI