经典排序之插入排序

 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 }

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

原文地址:https://www.cnblogs.com/newpanderking/p/2416490.html