归并排序

利用分治法和递归思想实现归并排序
#include<iostream>
using namespace std;
void MergeArray(int arr[], int first, int mid, int last, int temp[])
{
	int i = first, j = mid + 1;
	int k = 0;
	while (i <= mid && j <= last)
	{
		if (arr[i]<arr[j])
		{
			temp[k++] = arr[i++];
		}
		else
		{
			temp[k++] = arr[j++];
		}
	}
	while (i <= mid)
	{
		temp[k++] = arr[i++];
	}
	while (j <= last)
	{
		temp[k++] = arr[j++];
	}
	for (i = 0; i<k; i++)
	{
		arr[first + i] = temp[i]; 
	}

}
void Merge(int arr[], int left, int right, int temp[])
{
	if (left >= right)
		return;
	else
	{
		int mid = (left + right) / 2;
		Merge(arr, left, mid, temp);
		Merge(arr, mid + 1, right, temp);
		MergeArray(arr, left, mid, right, temp);
	}
}
void mergeSort(int arr[], int len)
{
	int *temp = new int[len];
	Merge(arr, 0, len - 1, temp);
	memcpy(arr, temp, sizeof(int)*len);
	delete[]temp;
}
int main()
{
	int arr[] = { 1,2,4,5,6,3,7,8};
	mergeSort(arr, sizeof(arr) / sizeof(int));
	for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
		cout<<arr[i]<<" ";
	cout << endl;
	return 0;
}

posted on 2017-04-18 11:12  ljbguanli  阅读(78)  评论(0编辑  收藏  举报