归并排序是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。
#include <cstdio>
void merge_sort(int *A, int x,int y,int *B) {
if(y-x > 1) {
int m = x +(y - x) / 2;
int p = x, q = m, i = x;
merge_sort(A, x, m, B);
merge_sort(A, m, y, B);
while(p < m || q < y) { if(q >= y || (p < m && A[p] <= A[q]))
B[i++] = A[p++];
else B[i++] = A[q++];
}
for(i = x; i < y; i++) A[i] = B[i];
}
}
int main() {
int n;
int A[100], B[100];
scanf("%d", &n);
for(int i = 0; i < n; i++) scanf("%d", &A[i]);
merge_sort(A, 0, n, B);
for(int i = 0; i < n; i++) printf("%d", A[i]);
return 0;
}
#include
void merge_sort(int *A, int low, int mid, int high, int *B) {
int i =low;
int j = mid + 1;
int k = low;
while(i <= mid && j <= high)
if(A[i] <= A[j])
B[k++] = A[i++];
else B[k++] = A[j++];
while(i <= mid)
B[k++] = A[i++];
while(j <= high)
B[k++] = A[j++];
for(k = low; k <= high; k++)
A[k] = B[k];
}
void mergesort(int *A,int low, int high, int *B) {
if(low < high) {
int mid = (low + high) / 2;
mergesort(A, low, mid, B);
mergesort(A, mid+1, high, B);
merge_sort(A, low, mid, high, B);
}
}
int main() {
int n;
int A[100], B[100];
scanf("%d", &n);
for(int i = 1; i <= n; i++)
scanf("%d", &A[i]);
mergesort(A, 1, n, B);
for(int i = 1; i <= n; i++)
printf("%d ", A[i]);
return 0;
}