归并排序

来源:互联网 发布:劲舞团淘宝 编辑:程序博客网 时间:2024/06/02 00:39

读了别人的程序,自己重写了一遍,完整代码如下:

#include<iostream>using namespace std;#define MAXSIZE 10void print(int a[],int size = MAXSIZE){   int i;for(i=0;i<size;i++)cout<<a[i]<<" ";cout<<endl;}void merge_array(int a[],int first,int mid,int last,int temp[]){   if(first>mid||mid>last) return;   int i,j,k;   i=first;   j=mid+1;   k=0;   while(i<=mid&&j<=last)   {   if(a[i]<=a[j])    temp[k++]=a[i++];   else    temp[k++]=a[j++];   }   while(i<=mid) temp[k++]=a[i++];   while(j<=last) temp[k++]=a[j++];   i=first;   k=0;   while(i<=last) a[i++]=temp[k++];}void merge_divide(int a[],int first,int last,int temp[]){   int mid;   if(first<last)   {   mid = (first+last)/2;   merge_divide(a,first,mid,temp);   merge_divide(a,mid+1,last,temp);   merge_array(a,first,mid,last,temp);   }}void merge_sort(int a[],int size,int temp[]){   if(size<=1) return;    merge_divide(a,0,size-1,temp);}int main(){   int a[MAXSIZE]={1,4,5,8,12,14,3,18,13,10};    int temp[MAXSIZE];merge_sort(a,MAXSIZE,temp);print(a);system("pause");return 1;}


参考地址:http://blog.csdn.net/morewindows/article/details/6678165#comments


原创粉丝点击