首页 > 代码库 > 【C++】归并排序

【C++】归并排序

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

好好学习,天天向上...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++】归并排序