[Data Structure] - Sorting (Part 2)

Preface: Our sorting has explained a series of methods in detail before, so we are now going to merge sort, so we will explain merge sort now.

Insert image description here

Merge sort:

Merge Sort (MERGE-SORT) is an effective sorting algorithm based on the merge operation. This algorithm is a very good version of the divide and conquer method (Divide and
Conquer). Typical applications. Merge the already ordered subsequences to obtain a completely ordered sequence; that is, first make each subsequence
ordered, and then make the subsequence segments orderly. If two ordered lists are merged into one ordered list, it is called a two-way merge.
Insert image description here

void _MergeSort(int* a, int begin, int end, int* tmp)
{
    
    
	if (begin >= end)
		return;

	int mid = (begin + end) / 2;
	// [begin, mid][mid+1, end]
	_MergeSort(a, begin, mid, tmp);
	_MergeSort(a, mid + 1, end, tmp);

	// [begin, mid][mid+1, end]归并
	int begin1 = begin, end1 = mid;
	int begin2 = mid + 1, end2 = end;
	int i = begin;
	while (begin1 <= end1 && begin2 <= end2)
	{
    
    
		if (a[begin1] < a[begin2])
		{
    
    
			tmp[i++] = a[begin1++];
		}
		else
		{
    
    
			tmp[i++] = a[begin2++];
		}
	}

	while (begin1 <= end1)
	{
    
    
		tmp[i++] = a[begin1++];
	}

	while (begin2 <= end2)
	{
    
    
		tmp[i++] = a[begin2++];
	}

	memcpy(a + begin, tmp + begin, sizeof(int) * (end - begin + 1));
}

a is the array we want to sort, which stores the data to be sorted. tmp is an additional array we have opened to store our sorted data, and we sort Well-ordered data is inserted tail-end into the array like a linked list. We first find the middle value and divide this interval into two small intervals, and the two small intervals are each divided into small intervals. Compare the elements in the two small intervals one by one from left to right, and put the smaller elements first into the additional array tmp. If the entire tail of a small interval is inserted into tmp, it will end. The loop is executed, and another array is inserted into tmp at the end in sequence. Finally, the data in our tmp is copied to the array a and it is completed.
Insert image description here

void MergeSort(int* a, int n)
{
    
    
	int* tmp = (int*)malloc(sizeof(int) * n);
	if (tmp == NULL)
	{
    
    
		perror("malloc fail");
		return;
	}

	_MergeSort(a, 0, n - 1, tmp);

	free(tmp);
}

This is used to open up additional array tmp. We pass parameters to the function _MergeSort, recursively complete the sorting in _MergeSort and then return, and then destroy the opened space.

If you can help me, please support it! Thank you everyone!

Supongo que te gusta

Origin blog.csdn.net/Lehjy/article/details/134914240
Recomendado
Clasificación