归并排序C++实现

#include <iostream>

using namespace std; 

int temp[100];
void Merge(int* a, int low, int mid, int high)
{
	int i = low;
	int j = mid + 1;
	int size = 0;
	for (; (i <= mid) && (j <= high); size++)
	{
		if (a[i] < a[j])
			temp[size] = a[i++];
		else
			temp[size] = a[j++];

	}
	while (i <= mid)
		temp[size++] = a[i++];
	while (j <= high)
		temp[size++] = a[j++];
	for (i = 0; i < size; i++)
		a[low + i] = temp[i];
}
void MergeSort(int* a, int low, int high)
{
	if (low >= high)
		return;
	int mid = (low + high) / 2;
	MergeSort(a,low,mid);
	MergeSort(a, mid+1, high);
	Merge(a, low, mid, high);

}
int main()
{
	int a[] = {3,56,3,7,45,8,1};
	int size = sizeof(a) / sizeof(int);
	MergeSort(a,0,size-1);
	for (int i = 0; i < 7; i++)
		cout << a[i] << endl;
}

posted @ 2016-03-27 11:11  牧羊少年10号  阅读(111)  评论(0编辑  收藏  举报