歸併排序

#include <stdio.h>
#include <stdlib.h>
#define MAX 255
int R[MAX];

void Merge(int low,int m,int high)
{/* 將兩個有序的子文件R[low..m)和R[m+1..high]歸併成一個有序的 */
 /* 子文件R[low..high] */
 int i=low,j=m+1,p=0; /* 置初始值 */
 int *R1; /* R1是局部向量,若p定義爲此類型指針速度更快 */
 R1=(int *)malloc((high-low+1)*sizeof(int));
 if(!R1) /* 申請空間失敗 */
 {
  puts("Insufficient memory available!");
  return;
 }
 while(i<=m&&j<=high) /* 兩子文件非空時取其小者輸出到R1[p]上 */
  R1[p++]=(R[i]<=R[j])?R[i++]:R[j++];
 while(i<=m) /* 若第1個子文件非空,則複製剩餘記錄到R1中 */
  R1[p++]=R[i++];
 while(j<=high) /* 若第2個子文件非空,則複製剩餘記錄到R1中 */
  R1[p++]=R[j++];
 for(p=0,i=low;i<=high;p++,i++)
  R[i]=R1[p];/* 歸併完成後將結果複製回R[low..high] */
} /* end of Merge */


void Merge_SortDC(int low,int high)
{/* 用分治法對R[low..high]進行二路歸併排序 */
 int mid;
 if(low<high)
 {/* 區間長度大於1 */
  mid=(low+high)/2; /* 分解 */
  Merge_SortDC(low,mid); /* 遞歸地對R[low..mid]排序 */
  Merge_SortDC(mid+1,high); /* 遞歸地對R[mid+1..high]排序 */
  Merge(low,mid,high); /* 組合,將兩個有序區歸併爲一個有序區 */
 }
}/* end of Merge_SortDC */


void main()
{
 int i,n;
 //clrscr();
 puts("Please input total element number of the sequence:");
 scanf("%d",&n);
 if(n<=0||n>MAX)
 {
  printf("n must more than 0 and less than %d.\n",MAX);
  exit(0);
 }
 puts("Please input the elements one by one:");
 for(i=1;i<=n;i++)
  scanf("%d",&R[i]);
 puts("The sequence you input is:");
 for(i=1;i<=n;i++)
  printf("%4d",R[i]);
 Merge_SortDC(1,n);
 puts("\nThe sequence after merge_sortDC is:");
 for(i=1;i<=n;i++)
  printf("%4d",R[i]);
 puts("\n Press any key to quit...");
 getchar();

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章