码迷,mamicode.com
首页 > 编程语言 > 详细

【C++】归并排序

时间:2016-10-10 19:31:25      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

还是紧张...还是不够熟练...

好好学习,天天向上...ORZ

===========我是一条咸鱼的分割线==============

思路:

  先递归分割,然后归并排序

技术分享

代码:

  

技术分享
 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 void merge(int* str1, int s, int m, int e) {
 6     int * p = new int[e - s + 1];
 7     int count = 0;
 8     for (int i = s, j = m + 1; i <= m || j <= e;) {
 9         if (i <= m && j <= e && str1[i] >= str1[j]) {
10             p[count++] = str1[j];
11             j++;
12         }
13         else if (i <= m && j <= e && str1[i] < str1[j]) {
14             p[count++] = str1[i];
15             i++;
16         }
17         else if (i > m && j <= e) {
18             p[count++] = str1[j];
19             j++;
20         }
21         else if (i <= m && j > e) {
22             p[count++] = str1[i];
23             i++;
24         }
25     }
26 
27     for (int i = s, j = 0; i <= e && j < count; i++, j++)
28         str1[i] = p[j];
29 
30     delete p;
31 }
32 
33 void mysort(int* num, int a, int b) {
34 
35     if (a >= b)return;
36 
37     int mid = (a + b) / 2;
38     if (b > a + 1) {
39         mysort(num, a, mid);
40         mysort(num, mid + 1, b);
41     }
42     merge(num, a, mid, b);
43 }
44 
45 
46 int main() {
47     int* num = new int[10];
48     int count = 10;
49 
50     for (int i = 0; i < 10; i++) {
51         cin >> num[i];
52     }
53 
54     mysort(num, 0, 9);
55 
56     for (int i = 0; i < count; i++)
57         cout << num[i] << " ";
58     cout << endl;
59 
60     system("pause");
61     return 0;
62 }
View Code

 

参考:http://www.cnblogs.com/skywang12345/p/3602369.html

【C++】归并排序

标签:

原文地址:http://www.cnblogs.com/cheermyang/p/5946441.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!