Analysis of the code analysis of the merge algorithm sorting in c and its stability and time complexity

**

Merge sort:

**
Merge sort code:

void _MergeSort(int *arr, int left, int right, int *extra)
{
	if (left + 1 >= right)
	{
		return;
	}

	int mid = left + (right - left) / 2;

	_MergeSort(arr, left, mid, extra);
	_MergeSort(arr, mid, right, extra);

	Merge(arr, left, mid, right, extra);
}
void MergeSort(int *arr, int size)
{
	int *extra = (int*)malloc(sizeof(int) * size);
	_MergeSort(arr, 0, size, extra);
	free(extra);
}
  • Merge sort is not the previous sorting mode of sorting from front to back or from back to front in order, but a merged way to sort. It uses the idea of ​​divide and conquer, which means it turns a large array into Many small arrays are then merged and sorted, so they will not be successfully sorted until the final merge into a large array. The specific method is to first divide the array into two small arrays, that is, calculate the intermediate coordinates, and then divide The left array and the right array, of course, are used here recursively, because there is no way to sort directly because it is only divided once (of course, you can also use other methods, but the merge cannot be sorted, because in the merge algorithm of merge sort There are several elements that need to be arranged several times, that is, n elements can be arranged only n times), so the problem lies in when they can be merged, that is, when both sides are in order, they can be merged. When are both sides in order, because we divide and conquer, we will not process it, so only when the left and right sides are both an element, it means that both sides are in order, so at this time it can be merged, because We have two recursions (one on the left and the other on the right), so only when the length of the left and right arrays are both 1, we call the merge function, that is, write this merge function under the two recursions, So how does this merge function realize that n elements are arranged n times, because before calling this merge function, we know that the elements on both sides are ordered with the middle coordinates as a reference, so it is simple, because they are at both ends Either the smallest or the largest (in ascending order, for example, the two ends are the smallest), just compare the size of the two ends to know who is the smallest, needless to say is the head element of another array with this element After the comparison, continue to compare other elements, because it is ordered as long as it is smaller than the first one, it must be smaller than the others, so it can be directly sorted. Here we pass an empty array in advance to store the combined ordered elements (Because although we are talking about two arrays, there is actually only one array. We distinguish between left and right by superscript, and it is said that there is only one element on the left and right recursively, which is actually a lie, but we just passed in The subscript of can access one element on the left and right. In fact, there are other elements in this array, so we need to use an empty array to put the ordered elements in), we must arrange it every time we compare An element (because it is ordered), just pass this element to the empty array, and then perform the ++ operation on the array with the arranged elements, because that element is already arranged, and the next element becomes the first A row, but the array that is not passed in does not need to change, because it does not know whether it is larger than the next element of the other array, so our two arrays are always in order, that is, every time the loop is executed Arrange one, it should be noted here that when all the elements of an array are arranged (that is, when the subscript of the middle element is arranged), it will break out of the loop, because there is no need to judge again, and the element is not arranged directly Press all the elements of the finished array directly Put the order in the empty array, because it must be in order, the ones in front of it have already been arranged, after finishing the arrangement, we will put the elements in this empty array into the previous array in order (because it may This array is also used in the upper layer, so the value of this array is disrupted), and a merge sort is completed, because we usually divide to the left first, so when the first merge is executed, It is equivalent to the left side of the previous layer is arranged, so it will go to the right, and after the right is arranged, return to this layer, and then merge again until there are only two parts on the last layer. After the merge is completed, it is completed Sort

Merging function code (ascending order):

void Merge(int *arr, int left, int mid, int right, int *extra)
{
	int sz = right - left;
	int extra_index = 0;
	int right_index = mid;
	int left_index = left;

	while(left_index < mid && right_index < right)
	{
		if (arr[left_index] <= arr[right_index])
		{
			extra[extra_index++] = arr[left_index++];
		}
		else
		{
			extra[extra_index++] = arr[right_index++];
		}
	}

	while (left_index < mid)
	{
		extra[extra_index++] = arr[left_index++];
	}

	while (right_index < right)
	{
		extra[extra_index++] = arr[right_index++];
	}

	for (int i = 0; i < sz; i++)
	{
		arr[left + i] = extra[i];
	}
}

Test Data:

int main() {
	int array[] = { 3, 9, 1, 4, 7, 8, 3, 5 };
	int size = sizeof(array) / sizeof(int);
	MergeSort(array, size);
	for (int i = 0; i < size; i++) {
		printf("%d ", array[i]);
	}
}

Test Results:

Analysis of the stability and time complexity of this merge function:

  • The time complexity of merge sort is mainly the sum of his decomposition time and the time used by the merge function. The reason for their sum is that the decomposition time has nothing to do with the merge time, because it is first decomposed, and after all decomposing, we will proceed. Combine, which means that the time spent in decomposition has been used, and then add the time for each combination, so they are in the relationship of and, and then the time spent in decomposition is O(n) because we are not just dividing to the left or to Right divide, but divide left and right at the same time, until there is only one element left on both sides, so every time you want to merge, at least every two elements have been merged once, which means that each element has been individually visited , So each element will be divided into separate elements, and then returned to the previous layer for merging, so a total of n-1 times (this decomposition method is actually selecting the largest or smallest, because there is only one number that does not need to be selected , Because there is no comparison, the two numbers must be selected once, because the size of the two numbers is not known, only when the two numbers are compared can be known, so there are several numbers that need to be compared several times, and there is no need to compare with yourself, merge and sort It's the same, except that after comparing the two numbers, the size of the two numbers is sorted out. You can find out by sorting each two only once. If there are four elements, it will sort twice first, and then put this row. Ok, these two sets of data are arranged together once, so the decomposition process is that you arrange several times to arrange, so at least each element must be arranged once), so it is O(n) time complexity, and then merge function Because we know that it is in order when we merge, we can arrange n according to n elements. There are only two elements in the first merge, so we arrange twice, and so on. At the end of the overall merge, we have n elements to be merged, so we arrange n times, because we split into two arrays for the first time, so the previous layer of the last layer needs to be merged twice, the left array and the right array, The number of elements in the left and right arrays is n / 2 + n / 2, that is, n elements are also n times, so how many elements in the previous layer have to be arranged, that is, n / 4 +… + n /4 = n, It is also n times, so how many n times there are, there are log n times, because it is decomposed in the form of a binary tree, that is, after the two elements at the bottom are merged, they must return to the upper level to merge the four elements. This goes up, so there are log n times, so the overall time complexity of the merge function is O( log n * n), we are used to writing it as O(n * log n), so its overall time complexity is O(n) = n + n * log n, so O(n * log n), then merge sort is a stable sorting method, because it is sorted in pairs first, even if it is separated, in two arrays The middle row will not affect each other, and it will be judged one by one when merging, so order and stability can be guaranteed

Intelligent Recommendation

Sorting algorithm merge sort and its time complexity and space complexity

Sorting algorithm merge sort and its time complexity and space complexity The efficiency of quick sort in the sorting algorithm is very high, but there is another sorting algorithm that can be compara...

Sorting algorithm-Hill sorting diagram, code implementation and time complexity analysis

Hill Sort (Shellsort) Hill sorting is one of the first algorithms to break the second time barrier. Hill sorting works by comparing elements separated by a certain interval; the distance used for each...

Common ten sorting algorithms C ++ implementation (time -to -space complexity, analysis of stability)

This article mainly describes the implementation and general thinking of the sorting algorithm. If you do not understand one of the algorithms, you can search for it first, look at the approximate pro...

Explosive sorting and its time, spatial complexity analysis

Sprinkle Concept and ideas: Repeatedly visiting the number to be sorted, comparing two elements at a time, if their order is wrong, exchange them. The work of visiting the number column is repeatedly ...

More Recommendation

Java implementation of classical sorting algorithm and complexity stability analysis

Sort Complexity O() reading Owen Average time complexity comparison: Bubbling: O(n^2) Insert: O(n^2) Select: O(n^2) Fast row: O(nlgn) Stability: Bubbling: Stable Insert: Stable Choice: Unstable Fast r...

Analysis of the stability of sorting algorithm

1. How does bubble sorting achieve stable sorting When judging if, strictly greater than (less than) is enough 2. How to achieve stable sorting by direct insertion sort? Same as bubbling 3. Why can't ...

Java implements eight classic sorting algorithms and their complexity, stability and code analysis

One, insertion sort 1.1 Direct insertion sort Space complexity:。 time complexity:. In the best case, the elements in the table are already in order. At this time, every time you insert an element, you...

Stability analysis of sorting algorithm (including java code)

First of all, the stability of the sorting algorithm should be known to everyone.Ensure that the two equal numbers before sorting are in the same order before and after the sequence, and that the orde...

Sorting algorithm quick sorting and time complexity analysis

Bubble sorting and performance optimization of sorting algorithm (time complexity + space complexity analysis) Sorting algorithm simple selection sorting and time complexity analysis Sorting algorithm...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top