#include "stdafx.h"
void MergeArray(int arr[], int first, int mid, int last, int temp[])
{
int i = first, j = mid + 1;
int k = 0;
while (i <= mid && j <= last)
{
if (arr[i] < arr[j])
temp[k++] = arr[i++];
else
temp[k++] = arr[j++];
}
while (i <= mid)
temp[k++] = arr[i++];
while (j <= last)
temp[k++] = arr[j++];
for (i = 0; i < k; i++)
arr[first + i] = temp[i];
}
void MergeSort(int a[],int first,int last,int temp[])
{
if(first<last)
{
int mid =(first + last)/2;
MergeSort(a,first,mid,temp);
MergeSort(a,mid+1,last,temp);
MergeArray(a,first,mid,last,temp);
}
}
int main(int argc, char* argv[])
{
int data[]={10,7,5,6,9,8,4,2,0,8,1,3,11};
int size=(sizeof(data)/sizeof(data[0]));
int * p=new int[size];
if(NULL==p)
return false;
MergeSort(data,0,size-1,p);
for(int i=0;i<size;i++)
{
printf("%d ",data[i]);
}
delete [] p;
int aaa;
scanf("%d",&aaa);
return 0;
}
归并排序
最新推荐文章于 2024-08-12 19:32:44 发布