当前位置: 移动技术网 > IT编程>开发语言>C/C++ > 学习了插入排序

学习了插入排序

2019年08月10日  | 移动技术网IT编程  | 我要评论

杜瓦瓶sybxitong,车人网,4k电视微鲸

简单的理解,插入排序,就是原队列中不断的出列一个值,与已经出列的所有值进行一一比较,找到自己的位置进行插队。

下面是学习的来的插入排序以及自己对一些代码的注释;另外,在此基础上将其中的插队代码,单独做成了一个函数。

下面是插入排序的c++代码:

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 template<class t>
 6 void insertionsort(t *p, int len);
 7 
 8 int main()
 9 {
10     int q[] = {8,5,7,4,0,9,6,2,3,1};
11     insertionsort(q, 10);
12     for(int i=0; i<10; i++)
13     {
14         cout << q[i] << ' ';
15     }
16     cout << endl;
17     return 0;
18 }
19 
20 template<class t>
21 void insertionsort(t *p, int len)
22 {
23     int line_up, wait;//line_up表示出列排队的总个数
24                     //wait表示等待出列的索引位置
25     for(wait=1; wait<len; wait++)
26     {
27         t tem = p[wait];
28         line_up = wait;//表示出列排队的最后位置
29                        //开始插入已经排好队的队列中(有line_up个值)
30         while(line_up>0 && p[line_up-1]>=tem)
31         {
32             p[line_up] = p[line_up-1];//将原来的值向后移动
33             line_up--;// 再看看下一个位置可不可以放tem
34         }
35         p[line_up] = tem;//索引位置选好后就可以插队了
36     }
37 }

改动的c++代码

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 template<class t>
 6 void insertionsort(t *p, int len);
 7 
 8 template<class t>
 9 void insert(const t& m, t *b, int j);
10 
11 int main()
12 {
13     int q[] = {8,5,7,4,0,9,6,2,3,1};
14     insertionsort(q, 10);
15     for(int i=0; i<10; i++)
16     {
17         cout << q[i] << ' ';
18     }
19     cout << endl;
20     return 0;
21 }
22 
23 template<class t>
24 void insertionsort(t *p, int len)
25 {
26     int line_up, wait;
27     for(wait=1; wait<len; wait++)
28     {
29         t tem = p[wait];
30         insert(tem, p, wait);
31     }
32 }
33 
34 template<class t>
35 void insert(const t& m, t *b, int j)
36 {
37     int i = j;
38     while(i>0 && b[i-1]>=m)
39     {
40         b[i] = b[i-1];
41         i--;
42     }
43     b[i] = m;
44 }

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网