插入排序【代码】

思路参考:

《算法导论》第三版P10

代码:

 1 // 171028插入排序.cpp: 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 #include <random>
 7 
 8 using namespace std;
 9 
10 void insertion_sort(unsigned int a[], int len)//按升序排列
11 {
12     unsigned int key = 0;
13     int j = 0;
14     for (int i = 0; i < len; i++)//依次取出原数组中的数
15     {
16         key = a[i];
17         j = i - 1;
18         while (j >= 0 && a[j] > key)//如果按降序排列则改成j >= 0 && a[j] < key
19         {
20             a[j + 1] = a[j];
21             j--;
22         }
23         a[j + 1] = key;
24     }
25     cout << "排序之后的数组序列: ";
26     for (int i = 0; i < len; i++)
27     {
28         cout << a[i] << ends;
29     }
30     cout << endl;
31 }
32 
33 int main()
34 {
35     default_random_engine e;
36     uniform_int_distribution<unsigned> u(0, 100);//便于测试方便,以后的数据全部用随机数
37     unsigned int test[15] = { 0 };
38     for (int i = 0; i < 15; i++)
39     {
40         test[i] = u(e);
41     }
42     cout << "排序之前的数组序列: ";
43     for (auto c : test)
44         cout << c << ends;
45     cout << endl;
46     insertion_sort(test, sizeof(test) / sizeof(test[0]));
47     return 0;
48 }

 

posted @ 2017-10-28 14:30  nullxjx  阅读(1307)  评论(0编辑  收藏  举报