#include<cstdio>
void Mergearray(int *a, int left, int mid, int right, int *tmp) {
int i = left;
int j = mid +1;
int k = 0;
int m = mid;
int n = right;
//二路归并
while(i <= m && j <= n) {
if(a[i] <= a[j]) {
tmp[k++] = a[i++];
}
else {
tmp[k++] = a[j++];
}
}
//处理子数组中剩余的元素
while(i <= m) {
tmp[k++] = a[i++];
}
while(j <= n){
tmp[k++] = a[j++];
}
//从临时数组中拷贝到目标数组中
for(i = 0; i < k; i++)
{
a[left+i] = tmp[i];
}
}
void MergeSort(int *a, int left, int right, int * tmp){
if(left < right) {
int mid = left + (right -left)/2;
//归并排序,使得是左边序列有序
MergeSort(a, left, mid, tmp);
//归并排序 使得右边的序列有序
MergeSort(a, mid+1, right, tmp);
//合并两个有序序列
Mergearray(a, left, mid, right, tmp);
}
}
void printNum(int a[], int n ){
for(int i =0; i < n; i++)
{
printf("%3d", a[i]);
}
}
int main()
{
int array[] = {6, 3, 2, 1, 4, 10, 9, 8, 7, 5};
int b[10];
MergeSort(array, 0, 9, b);
printNum(array, 10);
return 0;
}
归并排序
最新推荐文章于 2022-09-17 00:46:29 发布