Sorting algorithm-----Merge sort

Table of contents

Foreword:

merge sort

1. Definition

2. Explanation of algorithm process

2.1 General idea

2.2 Graphical examples

Split synthesis steps

 Edit

Related dynamic graphics 

 3. Code implementation (C language)

4. Algorithm analysis

4.1 Time complexity

4.2 Space complexity

 4.3 Stability


Foreword:

        Today we will start to learn a new sorting algorithm - merge sort. When it comes to merge sort, the most important idea is to divide and conquer, divide first and then conquer. Compared with the sorting algorithms learned previously, the merge sort process is relatively complicated, but don’t panic! I’ll explain the process in detail! Let’s learn together below!

merge sort

1. Definition

        Merge sort is an effective and stable sorting algorithm based on merge operations . This algorithm is a very typical application of the divide and conquer method . Merge the already ordered subsequences to obtain a completely ordered sequence; that is, first make each subsequence orderly, and then make the subsequence segments orderly. If two ordered lists are merged into one ordered list, it is called a two-way merge.

2. Explanation of algorithm process

2.1 General idea

Given an array arr[0,n-1], split the array into arr[0,n/2] and arr[n/2+1,n-1] and then further halve the array. Split until there is only one element in each fractional array, then end the split; then enter the sorting, sort and merge according to the path of the splitting process, until it is merged into an array, and the final array is the sorted array array.

Merge sort uses the divide-and-conquer idea. The divide-and-conquer mode has three steps at each level of recursion:

  • Divide : Divide n elements into subsequences containing n/2 elements.
  • Solution (Conquer) : Use the merge sort method to recursively sort two subsequences.
  • Combine : Merge two sorted subsequences to obtain the sorted result.

2.2 Graphical examples

Split synthesis steps

Given an array [6,5,3,1,8,7,2,4], it is required to sort through merge sort

The first step is to split it one by one until there is only one element left in each fractional group, as shown below:

                                                 6 5 3 1 8 7 2 4

First split              6 5 3 1 8 7 2 4                              

Second split          6 5  3 1  8 7 2 4                                       

The third split        6 5 3 1 8 7 2 4

In the second step , after the split is completed, sort and merge, as shown below:

                            6        5       3        1        8        7       2        4

First merge:          5 6                1 3              7 8               2 4      

Second merge:                  1 3 5 6                            2 4 7 8

The third merge:                              1 2 3 4 5 6 7 8

 The above steps complete the merge sorting process. The demonstration diagram is as follows:

 

 

 dynamic picture:

 

Related dynamic graphics 

 3. Code implementation (C language)

#include<stdio.h>
//归并排序
//合成排序
void merge(int* n,int *temp,int left,int mid,int rigth) {
	int l_pos = left;
	int r_pos = mid+1;
	int pos = left;
	while (l_pos <= mid && r_pos <= rigth) {
		if (n[l_pos] < n[r_pos])
			temp[pos++] = n[l_pos++];
		else
			temp[pos++] = n[r_pos++];
	}
	while (l_pos <= mid)
		temp[pos++] = n[l_pos++];
	while (r_pos <= rigth)
		temp[pos++] = n[r_pos++];
	while (left <= rigth) {
		n[left] = temp[left];
		left++;
	}

}
//拆分与归并
void msort(int *n,int *temp,int left,int right) {
	if (left < right) {
		int mid = (left + right) / 2;
		msort(n, temp, left, mid); //左边
		msort(n, temp, mid+1, right);//右半
		merge(n, temp, left, mid, right);
	}
}
//排序函数接口(整体)
void merge_sort(int* n, int length) {
	int* temp = (int*)malloc(sizeof(int) * length);
	if (temp) {
		msort(n, temp, 0, length-1);
		free(temp);
	}
	else {
		printf("Space allocation failure");
	}
}

int main() {
	int array[8] = { 25,24,6,65,11,43,22,51 };
	printf("排序前:");
	for (int i = 0; i < sizeof(array) / sizeof(int); i++) {
		printf("%d ", array[i]);
	}
	printf("\n排序后:");
	merge_sort(array, sizeof(array) / sizeof(int));
	for (int i = 0; i < sizeof(array) / sizeof(int); i++) {
		printf("%d ", array[i]);
	}
}
//排序前:25 24 6 65 11 43 22 51
//排序后:6 11 22 24 25 43 51 65

4. Algorithm analysis

4.1 Time complexity

        Merge sort is second only to quick sort and is quite fast. Because merge sort operates on adjacent data each time, the time complexity of merge sort is O(nlogn) .

4.2 Space complexity

 Did you know that the time complexity of merge sort is always O(nlogn) under any circumstances? Isn’t it strange? Don't worry, everything has its own gains and losses. Merge sort reduces time complexity by sacrificing space. The above code involves the opening of data temporary storage space. The maximum number of spaces opened will not exceed n, so the space complexity is O(n)

 4.3 Stability

Merge sort is a stable sorting algorithm because the relative position of the same elements does not change either during the sorting and dismantling process or during the merging process, so it is stable.

 Okay, that’s all for today, have you learned it? See you in the next issue!

Guess you like

Origin blog.csdn.net/m0_73633088/article/details/132911514