归并排序算法的c++实现

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

/**
 *  Email 956324914@qq.com
 *  Author xlf
 */
 
/**
 * Merge functions merges the two sorted parts. Sorted parts will be from [left, mid] and [mid+1, right].
 */
template<typename T>
	static void merge_(T *array, int left, int mid, int right) {
		/*We need a Temporary array to store the new sorted part*/
		T tempArray[right-left+1];
		int pos=0,lpos = left,rpos = mid + 1;
		while(lpos <= mid && rpos <= right) {
			if(array[lpos] < array[rpos]) {
				tempArray[pos++] = array[lpos++];
			}
			else {
				tempArray[pos++] = array[rpos++];
			}
		}
		while(lpos <= mid)  tempArray[pos++] = array[lpos++];
		while(rpos <= right)tempArray[pos++] = array[rpos++];
		int iter;
		/* Copy back the sorted array to the original array */
		for(iter = 0;iter < pos; iter++) {
			array[iter+left] = tempArray[iter];
		}
		return;
	}

/**
 * sort an array from left->right 
 */
template<typename T>
	static void merge_sort(T *array, int left, int right) {
		int mid = (left+right)/2;
		/* We have to sort only when left<right because when left=right it is anyhow sorted*/
		if(left<right) {
			/* Sort the left part */
			merge_sort(array,left,mid);
			/* Sort the right part */
			merge_sort(array,mid+1,right);
			/* Merge the two sorted parts */
			merge_(array,left,mid,right);
		}
	}
	
/**
 * print all of the elements in `list` with size `n`
 */
template<typename T>
	static void printlist(T & list,int count) {
		int i;
		for(i=0;i<count;i++)
			printf("%d\t ",list[i]);
		printf("\n");
	}
	
int main()
{
	const int MAX_ELEMENTS = 20;
	int list[MAX_ELEMENTS];

	int i = 0;
	// generate random numbers and fill them to the list
	for(i = 0; i < MAX_ELEMENTS; i++ ){
		list[i] = rand()%100;
	}

	printf("The list before sorting is:\n");
	printlist(list,MAX_ELEMENTS);

	// sort the list using quicksort
	merge_sort<int>(list,0,MAX_ELEMENTS-1);

	// print the result
	printf("The list after sorting using merge sort algorithm:\n");
	printlist(list,MAX_ELEMENTS);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值