经典排序之插入排序

本文通过一个具体的C++代码示例详细介绍了如何实现插入排序算法。文章首先定义了一个包含多个整数的数组,并使用插入排序算法对其进行升序排列。在排序过程中,通过循环找到每个待插入元素的正确位置并将之前的元素向后移动来为新元素腾出空间。
 1 #include <iostream>
2 #include <stdio.h>
3 #include <string.h>
4 using namespace std;
5
6 int main()
7 {
8 int i,j,tem;
9 int length;
10 int a[]={2,43,24,19,25,39,11,6,5};
11 // length = a.length();
12 length = sizeof(a)/sizeof(int);
13 cout<<length<<endl;
14 printf("Before ordered:\n");
15 for(i = 0; i < length; i++)
16 printf("%d ",*(a+i));
17 printf("\n\n");
18 for(i = 1; i < length; i++)
19 {
20 j = i-1;
21 tem = a[i];
22 while(j>=0 && a[j]>tem)
23 {
24 a[j+1] = a[j];
25 j--;
26 }
27 a[j+1] = tem;
28 }
29 printf("After ordered:\n");
30 for(i = 0; i < length; i++)
31 printf("%d ",*(a+i));
32 printf("\n");
33 return 0;
34 }

插入排序用数组模拟如上,首先确定要排的为升序还是降序,然后找到每个元素要插入的位置,从第二个元素开始插入,找到位置后将钙元素插入,从插入的位置到该元素原来的位置中间的元素均向后移动一个位置。依次循环。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值