归并排序

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<time.h>
#define ARR_SIZE 100

int data[ARR_SIZE];

void mergeSort(int,int);
void merge(int,int,int);
int main()
{
	int i=0,result=0;
	srand((int)time(0));
	for(i=0;i<ARR_SIZE;i++)
	{
		data[i] = (int)(rand());
		printf("%d ",data[i]);
	}
	printf("\nAfter MergeSorting:\n");
	mergeSort(0,ARR_SIZE-1);
	for(i=0;i<ARR_SIZE;i++)
		printf("%d ",data[i]);
	return 0;
}

void mergeSort(int low,int high)
{
	int mid=0;
	if(low<high)
	{
		mid=(low+high)/2;
		mergeSort(low,mid);
		mergeSort(mid+1,high);
		merge(low,mid,high);
	}
}

void merge(int low,int mid,int high)
{
	int i, k;
	int *temp = (int *) malloc((high-low+1) * sizeof(int)); //申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列
	int begin1 = low;
	int end1 = mid;
	int begin2 = mid + 1;
	int end2 = high;
 
	for (k = 0; begin1 <= end1 && begin2 <= end2; ++k)  //比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置
		if(data[begin1]<data[begin2])
			temp[k] = data[begin1++];
		else
			temp[k] = data[begin2++];	
	while(begin1<=end1) //若第一个序列有剩余,直接拷贝出来粘到合并序列尾
		temp[k++] = data[begin1++];
	while(begin2<=end2) //若第二个序列有剩余,直接拷贝出来粘到合并序列尾
		temp[k++] = data[begin2++];
	for (i = 0; i < (high-low+1); i++) //将排序好的序列拷贝回数组中
		data[low+i] = temp[i];
	free(temp);
}

posted on 2010-10-26 17:07  Goofy  阅读(136)  评论(0编辑  收藏  举报