归并排序题目整理归并(hdu)


hdu2019数列有序

 1 #include 
 2 using namespace std;
 3 int A[101];
 4 int main()
 5 {
 6     int m,n;
 7     void Merge(int p,int q,int r);
 8     while(cin >> n >> m){
 9             if(n == 0&&m ==0) break;
10             for(int i = 0;i < n;i++) cin >> A[i];
11             A[n] = m;
12             Merge(0,n-1,n);
13             for(int i = 0;i < n;i++) cout << A[i] << " ";
14             cout << A[n] << endl;
15     }
16     return 0;
17 }
18 void Merge(int p,int q,int r){
19     int n1 = q - p + 1;
20     int n2 = r - q;
21     long long L[n1],R[n2];
22     for(int i = 0;i < n1;i++) L[i] = A[i+p];
23     for(int i = 0;i < n2;i++) R[i] = A[i+q+1];
24     L[n1] = 100000000;R[n2] = 100000000;
25     int i = 0;int j = 0;
26     for(int k = p;k <= r;k++){
27             if(L[i] < R[j]) A[k] = L[i++];
28             else A[k] = R[j++];
29     }
30 }

hdu1040As Easy As A+b

 1 #include
 2 using namespace std;
 3 int A[1000];
 4 int main()
 5 {
 6     void Merge(int p,int q,int r);
 7     void Merge_sort(int p,int q);
 8     int num;int m,n;
 9     cin >> num;
10     while(num--){
11             cin >> n;
12             for(int i = 0;i < n;i++) cin >> A[i];
13             Merge_sort(0,n-1);
14             for(int i = 0;i < n - 1;i++) cout << A[i] << " ";
15             cout << A[n-1] << endl;
16     }
17     return 0;
18 }
19 
20 void Merge(int p,int q,int r)
21 {
22     int n1 = q - p + 1;
23     int n2 = r - q;
24     long long L[n1],R[n2];
25     //将原数列分到两个数列
26     for(int i = 0;i < n1;i++) L[i] = A[i+p];
27     for(int i = 0;i < n2;i++) R[i] = A[i+q+1];
28     L[n1] = 100000000;R[n2] = 100000000;//作为哨兵
29     int i = 0;int j = 0;
30     //接下来进行排序
31     for(int k = p;k <= r;k++){
32             if(L[i] < R[j]) A[k] = L[i++];
33             else A[k] = R[j++];
34     }
35 }
36 void Merge_sort(int p,int q)
37 {
38     int l;
39     if(p - q == 1) {
40             if(A[q] < A[p]){l = A[q];A[q] = A[p];A[p] = l;}}
41     else if(q - p) {
42             int center = (p + q) / 2;
43             Merge_sort(p,center);
44             Merge_sort(center + 1,q);
45             Merge(p,center,q);
46     }
47 }


你可能感兴趣的:(算法整理)