归并算法实现
A recursive merge sort algorithm used to sort an array of 7 integer values. These are the steps a human would take to emulate merge sort (top-down).
Complexity
Name | Best | Average | Worst | Memory | Stable | Comments |
---|---|---|---|---|---|---|
Merge sort | n log(n) | n log(n) | n log(n) | n | Yes |
1.对分割的左右两数据进行比较,并且合并。
int *B=(int *)malloc((n+1)*sizeof(int)) void MergeSort(int A[],int low,int mid,int high){ int i,j,k; for(int k=low,k<=high;k++)B[k]=A[k] for(i=low,j=mid+1,k=i;i<=mid&&j<=high;k++){ if(B[i]<=B[j])A[k]=B[i++]; else A[k]=B[j++]; } while(i<=mid)A[k++]=B[i++] while(j<=high)A[k++]=B[j++] }
2.基于分治的递归
void MergeSort(int A[],int low, int high){ if(low<high){ int mid=(low+high)/2; MergeSort(low,mid); MergeSort(mid+1,high); Merge(A,low,mid,high); } }