分治算法一(归并排序)

/* file: merge_sort			*/
/* 1、if n = 1  done			*/
/* 2、divide:A[1..n/2] and A[n/2+1..n] */
/* 3、merge 2 sorted subarray           */

#include<stdio.h>
#include <stdlib.h>

/*=====================================
  Array: the array to be ordered
  left :the left point of the array
  mid  : the middle point of the array
  right: the right point of the array
  Aux  : an array used to storage
=======================================*/
void MergeArray(int* Array, int left, int mid, int right, int* Aux)
{
	int i,j,k;
	//copy the array to the aux, left subarray in order
	for(i = mid + 1; i > left; i--)
		Aux[i-1] = Array[i-1];
	//copy the array to the aux, right subarray in reversed order
	//so that i and j will meet at the middle of the array
	for(j = mid; j < right; j++)
		Aux[right+mid-j] = Array[j+1];
	//merge the two subarrays
	for(k = left; k <= right; k++)
		if(Aux[j] < Aux[i])
			Array[k] = Aux[j--];
		else
			Array[k] = Aux[i++];
}

/*=====================================
  Array: the array to be ordered
  left :the left point of the array
  right: the right point of the array
  Aux  : an array used to storage
=======================================*/
void MergeSort(int* Array, int left,int right,int* Aux)
{
	int mid = (left + right)/2;
	if(left < right)
	{
		//sort the left subarray
		MergeSort(Array,left,mid,Aux);
		//sort the right subarray
		MergeSort(Array,mid+1,right,Aux);
		//merge the two sorted subarrays
		MergeArray(Array,left,mid,right,Aux);
	}
}

void main()
{
	int n,i;

	printf("Please input the length of Array<0:exit>:\n");
	while(scanf("%d",&n),n)
	{	
		//create two arrays of length n
		int* Array = new int[n];
		int* Aux = new int[n];
		//get the input integers
		printf("Please input %d integers:\n",n);
		for(i = 0; i < n; i++)
			scanf("%d",&Array[i]);
		//use mergesort algorithom
		MergeSort(Array,0,n-1,Aux);
		//print the sorted array
		printf("Sorted Array:\n");
		for(i = 0; i < n; i++)
			printf("%d ",Array[i]);
		system("pause");
		system("cls");
		//delete the two arrays
		delete[] Array;
		delete[] Aux;
		printf("Please input the length of Array<0:exit>:\n");
	}
}
归并排序的特性:
  (1)对N个元素的文件进行排序,它的运行时间与NlogN 成比例,与输入数据无关;
  (2)如果使用的归并算法是稳定的,则归并排序是稳定的;
  (3)归并排序使用与N成正比的额外内存空间;
Array
ij
sortedsorted
left         mid              right

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值