Common sorting algorithm (04) - merge sort

First, the basic idea of ​​merge sort

Merge sort is to use a recursive decomposition, a scale n n of the scale of the problem into two n / 2 n/2 issue, and then continue to proceed to the final size of recursive decomposition 1 1 problem. Then gradually from small-scale results are combined to finally obtain complete results. That is the idea of divide and rule.
Illustrating follows:Original Address
Here Insert Picture Description


Second, the algorithm analysis

Merge sort mode using space for time, with a result of each auxiliary array to store the sorted, and then copy it to a position corresponding to the original array, will correspond to the original values in the array at the position overwritten.
1 sort results, such as an array [4,3,2,1] recursive sub-problem is [4,3] and [2,1] wherein the first [4,3] on the size of the auxiliary array temp (temp of the size of the original array arr). Then sorted result in the temp array arr copied to a corresponding location on the array, as shown in FIG. This process is recursive merge sort.
Here Insert Picture Description
2, after the first sorting result recursion as follows

Here Insert Picture Description

Third, the code

#include<iostream>
#include<string>
using namespace std;

void Merge(int *arr, int *temp, int left, int mid,int right)
{
	int i = left;  //左边递归数组的指针
	int j = mid + 1; //右边递归数组的指针
	int index = 0;

	while (i <= mid && j<=right)
	{
		if (arr[i] < arr[j])
		{
			temp[index++] = arr[i++];
		}
		else
		{
			temp[index++] = arr[j++];			
		}
	}
	while (i <= mid)
	{
		temp[index++] = arr[i++];
	}
	while (j <= right)
	{
		temp[index++] = arr[j++];
	}

	index = 0;
	while (left <= right)
		arr[left++] = temp[index++];

}

void MergeSort(int *arr, int *temp, int left,int right)
{
	
	if (left < right)
	{
		int mid = left + (right - left) / 2;
		MergeSort(arr, temp, left, mid);   //左边归并排序,使得左子序列有序
		MergeSort(arr, temp, mid + 1, right); //右边归并排序,使得右子序列有序
		Merge(arr, temp, left, mid, right);   //将两个有序子数组合并排序
	}
}

int main()
{
	int arr[] = { 4,3,2,1 };
	int len = sizeof(arr) / sizeof(arr[0]);
	//创建一个长度等于原数组长度的辅助数组,避免递归中频繁开辟空间
	int *temp = new int[len];

	MergeSort(arr,temp, 0, len-1);
	delete[] temp;

	for (int i = 0; i < len; ++i)
		cout << arr[i] << " ";

	cout << endl;

	system("pause");
	return 0;
}

Results are as follows:
Here Insert Picture Description

Fourth, the complexity analysis

  • Space complexity O ( n ) O (n)
  • The time complexity is O ( n l O g n ) O (nlogn)

: References
graphic sorting algorithms (d) of the merge sort
merge sort summary of the ranking algorithm

Published 213 original articles · won praise 48 · views 110 000 +

Guess you like

Origin blog.csdn.net/Jeffxu_lib/article/details/104829361