7 merge sort

Merge sort is a typical application of divide and conquer. It belongs to non-in-situ sorting.

 

(1) Ideas:

Merge sort is to merge two ordered lists into a new ordered list.

That is, the sequence to be sorted is divided into several sub-sequences, and each sub-sequence is ordered. Then the ordered subsequences are merged into the overall ordered sequence.

 

(2) Complexity analysis:

(2.1) Time complexity:   

For a file of length n, logn merging is required, and the time for each merging is O(n), so the time complexity is O(nlogn).

(2.2) Space complexity:

         O (n)。

 

(3) Stability:

         Merge sorting is to recursively divide the sequence into short sequences. The recursive exit is that the short sequence has only 1 element (think of direct order) or 2 sequences (1 comparison and exchange), and then merges the ordered segments into one sequence. Long sequence of sequence, continue to merge until the original sequence is all sorted. It can be found that when there are 1 or 2 elements, one element will not be exchanged, and if the two elements are equal in size, no one deliberately exchanges it. This will not destroy the stability.

Then, in the process of merging short orderly sequences, is stability damaged? No. During the merging process, we can guarantee that if the two current elements are equal, we save the elements of the previous sequence in front of the result sequence, thus ensuring stability. Therefore, merge sort is also a stable sorting algorithm.

 

code segment:

void merge_sort(int source[],int tmp[],int start,int end)
{
	if(start<end)
	{
		int mid=start+(end-start)/2;
		//递归拆分
		merge_sort(source,tmp,start,mid);
		merge_sort(source,tmp,mid+1,end);
		//归并
		merge(source,tmp,start,mid,end);
	}
}

void merge(int source[],int tmp[],int start,int mid,int end)
{
	int i=start,j=mid+1,k=start;

	while( i!=mid+1&&j!=end+1 )
	{
		if(source[i]>=source[j])
		{
			tmp[k++]=source[j++];
		}
		else
		{
			tmp[k++]=source[i++];
		}
	}
	while(i!=mid+1)
	{
		tmp[k++]=source[i++];
	}
	while(j!=end+1)
	{
		tmp[k++]=source[j++];
	}

	for(i=start;i<=end;i++)
	{
		source[i]=tmp[i];
	}
}

 

Guess you like

Origin blog.csdn.net/u012906122/article/details/103601838