#include <stdio.h>
#include <stdlib.h>
//To save space, only one temp array is used
void mergeArray(int a[], int first, int mid, int last, int temp[]){
int i = first, j = mid + 1;
int m = mid, n = last;
int k = 0;
while(i <= m && j <= n){
if(a[i] < a[j]){
temp[k++] = a[i++];
}else{
temp[k++] = a[j++];
}
}
while(i <= m){
temp[k++] = a[i++];
}
while(j <= n){
temp[k++] = a[j++];
}
for(i = 0; i < k; i++){
a[first+i] = temp[i];
}
}
void mergesort(int a[], int first, int last, int temp[]){
if(first < last){
int mid = (first + last)/2;
//Devide
mergesort(a, first, mid, temp);
mergesort(a, mid + 1, last, temp);
//Conquer
mergeArray(a,first, mid, last,temp);
}
}
int main()
{
int a[] = {48, 6, 57, 42, 60, 72, 88, 73, 83, 85};
int temp[20];
mergesort(a, 0, 9, temp);
int i;
for(i = 0; i < 9; i++){
printf("%d\n",a[i]);
}
return 0;
}
Merge Sort
最新推荐文章于 2024-08-13 09:54:25 发布