歸並算法實現


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).

Merge Sort

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);

  }        

}

 

  


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com