其他分享
首页 > 其他分享> > 归并排序模版

归并排序模版

作者:互联网

 

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 #include <string>
 5 #include <cstdio>
 6 using namespace std;
 7 int a[100010];
 8 int temp[100010];
 9 void Merge(int l, int mid, int r) {
10     for (int i = l; i <= r; i++) temp[i] = a[i];
11     int i = l, j = mid + 1, k = l;
12     while (i <= mid && j <= r) {
13         if (temp[i] <= temp[j]) {
14             a[k++] = temp[i++];
15         }else {
16             a[k++] = temp[j++];
17         }
18     }
19     while (i <= mid) a[k++] = temp[i++];
20     while (j <= r) a[k++] = temp[j++];
21 }
22 void Mergesort(int l, int r) {
23     if (l >= r) return;
24     int mid = (l+r) / 2;
25     Mergesort(l,  mid);
26     Mergesort(mid+1, r);
27     Merge(l, mid, r);
28 }
29 
30 int main()
31 {
32     int n, m;
33     while (cin >> n)
34     {
35         if (n == 0)break;
36         cin >> m;
37         for (int i = 0; i < n; i++)
38         {
39             cin >> a[i];
40         }
41         //quick_sort(a, 0, n-1);
42         Mergesort(0, n-1);
43         if (m == 0)
44         {
45             for (int i = 0; i < n - 1; i++)
46             {
47                 cout << a[i] << " ";
48             }
49             cout << a[n - 1] << endl;
50         }
51         else{
52             for (int i = n - 1; i > 0; i--)
53             {
54                 cout << a[i] << " ";
55             }
56             cout << a[0] << endl;
57         }
58     }
59     
60 
61     return 0;
62 }

 

标签:Mergesort,归并,include,cout,int,模版,mid,cin,排序
来源: https://www.cnblogs.com/--lr/p/16261508.html