归并排序的使用

不多说 先上模板

#include<stdio.h>
void carry(int a[],int first,int mid,int last,int temp[])//将两个有序的数组合并
{
  int i=first,j=mid,m=mid+1,n=last,k=0;
  while(i<=j&&m<=n)//  比较两个数组的第一位  将较小的数放入temp 直到一个数组遍历结束 
  {
   if(a[i]<a[m])
   temp[k++]=a[i++];
   else temp[k++]=a[m++];
  }
  while(i<=j) temp[k++]=a[i++];
  while(m<=n) temp[k++]=a[m++];
  for(i=0;i<k;i++)
  {
      a[first++]=temp[i];// 将排序好的数组放回 a

  }
}
void sort(int a[],int first,int last,int temp[])// 不断的将数组二分直到数组的长度为1 然后依次有序合并(有点像二叉树原理)
{
  int mid;
  if(first<last)// 长度为一的时候结束
  {
      mid=(first+last)/2;
      sort(a,first,mid,temp);
      sort(a,mid+1,last,temp);// 不断二分
      carry(a,first,mid,last,temp); //将分好的两个数组有序合并
  }

}
int main()
{
 int a[10]={0,7,1,2,9,5,4,6,8,3},temp[12],i;
 sort(a,1,9,temp);
 for(i=1;i<=9;i++) printf("%d",a[i]);
 return 0;
}

posted @ 2016-03-31 15:49  猪突猛进!!!  阅读(255)  评论(0编辑  收藏  举报