排序算法06-归并排序




归并排序

大佬的归并排序详解

void mergeSort(vector<int>&arr, int start, int end)
{
	if (arr.empty()||start >= end)
		return;
	int mid = (end + start) / 2;

	mergeSort(arr, start, mid);
	mergeSort(arr, mid+1, end);

	merge(arr, start, mid, end);
	for (int i = 0; i < arr.size(); i++)
	{
		cout << arr[i]<<" ";
	}
	cout << endl;
}

///对两个数组进行合并 并排序
void merge(vector<int>&arr, int start, int mid, int end)
{
	vector<int> tmp;

	int i = start;
	int j = mid+1;

	while (i <= mid&&j <= end)
	{
		if (arr[i] <= arr[j])
			tmp.push_back(arr[i++]);
		else
			tmp.push_back(arr[j++]);
	}
	while(i <= mid)
		tmp.push_back(arr[i++]);
	while (j <= end)
		tmp.push_back(arr[j++]);

	for (int i = 0; i < tmp.size(); i++)
		arr[start + i] = tmp[i];
}

posted @ 2020-06-08 12:09  Fflyqaq  阅读(109)  评论(0编辑  收藏  举报