什么是分治法
分解-->解决-->合并
归并排序
#include<stdio.h>
#include<math.h>
//
void Merge(int A[], int p, int q, int r) {
int i, j, k;
int L[50], R[50];
int n1 = q - p + 1, n2 = r - q;
//为L和R数组赋值
for (i = 0; i < n1; i++) {
L[i] = A[p + i];
}
for (j = 0; j < n2; j++) {
R[j] = A[j + q + 1];
}
L[n1] = 10;
R[n2] = 10;
for (k = p; k < r + 1; k++) {
if (L[i] < R[j]) {
A[k] = L[i];
i++;
}
else {
A[k] = R[j];
j++;
}
}
}
void MergeSort(int A[], int p, int r) {
int q;
if (p < r) {
q = (p + r) / 2;
MergeSort(A, p, q);
MergeSort(A, q + 1, r);
Merge(A, p, q, r);
}
}
int main() {
int A[] = {9,4,6,1,7,2,8,3,0,10};
MergeSort(A, 0, 9);
for (int i = 0; i < 10; i++) {
printf("%d ", A[i]);
}
return 0;
}
标签:10,MergeSort,int,分治,++,n1,n2
From: https://www.cnblogs.com/liuzijin/p/17804147.html