排序 之 归并排序(二路)

#include<stdio.h>
#include<stdlib.h>//rand()


const int N = 10;
struct node
{
	int key;
	int num;
}n[N],t[N];




void merge(struct node s[], int low, int mid, int high, struct node temp[])
{
	int i,j,k;
	i=low,j=mid+1,k=0;
	while (i<=mid&&j<=high)
	{
		if (s[i].key<=s[j].key)
		{
			temp[k].key = s[i].key;
			i ++;
			k ++;
		}
		else
		{
			temp[k].key = s[j].key;
			j ++;
			k ++;
		}
	}
	while (i<=mid)
	{
		temp[k++].key = s[i++].key;//和if里面一样的效果
	}
	while (j<=high)
	{
		temp[k++].key = s[j++].key;
	}


	for (i=0; i<k; i++)
	{
		s[low+i] = temp[i];
	}
}


void merge_sort(struct node s[],int low,int high,struct node temp[])
{
	//printf("in merge_sort \n");
	int mid;
	
	if (low < high)
	{
		mid = (low+high)/2;
		merge_sort(s,low,mid,temp);//左边归并排序
		merge_sort(s,mid+1,high,temp);//右边归并排序
		merge(s,low,mid,high,temp);//
		//printf("in inner esle");
	}
}


int main()
{
	int i;
	struct node *p = new struct node [N];
	for (i=0;i<N;i++)
	{
		n[i].key = rand()%100;
		t[i].key = n[i].key;
		printf("%d\t",n[i].key);
	}
	
	merge_sort(n,0,N-1,p);
	delete [] p;
	printf("after sort:\n");
	for (i=0;i<N;i++)
	{
		//printf("i = ",i);
		printf("%d\t",n[i].key);
	}
	printf("\n");
	return 0;
}


归并排序的设计,类似于二分查找,属于分治策略。


你可能感兴趣的:(归并排序,merge,外排)