Divide and conquer: merge sort

Divide and conquer: merge sort

Divide and conquer: general steps

  1. Decompose the original problem into multiple sub-problems
  2. Solve sub-problems recursively solve each sub-problem
  3. Combine problem solutions to merge the results into the original problem solution

Merge sort

Basic idea: "Merge"
two or more ordered subsequences into an ordered sequence. In internal sorting, 2-way merge sorting is usually used . That is, the two adjacent records are ordered subsequences.

Insert picture description here

Algorithm flow:

  1. The array of A[1,n]scheduling problems decomposed into A[1,n/2]and A[n/2 +1,n]Scheduling

  2. Recursively solve the sub-problem to get two ordered sub-arrays

  3. Combine two ordered sub-arrays into one ordered array

    Merge sort: an array of decomposition, handed owned solved together and sort

The procedure is as follows (from small to large):

void merge_sort(int *A, int L, int R, int *T){
    
    
	if(R-L > 1){
    
    
		int M = L + (R-L)/2;	//划分
		int l = L, m = M, i = L;
		
		merge_sort(A, L, M, T);	//递归求解 
		merge_sort(A, M, R, T);	//递归求解 
		
		while(l<M || m<R){
    
    
			if(m>=R || (l<M && A[l]<=A[m]))
				T[i++] = A[l++];	//从左半数组复制到临时空间 
			else
				T[i++] = A[m++];	//从右半数组复制到临时空间 
		} 
		
		for(i=L; i<R; i++)	//从辅助空间复制回 A 数组 
			A[i] = T[i];
	}
}

The time complexity of merging and sorting n records is O(nlog 2 n). which is:

  1. The time complexity of each merge is O(n);
  2. A total of log 2 n passes are required.

example:

Title description
Given you an integer sequence of length n. Please use merge sort to sort this series from smallest to largest. And output the sorted sequence in order.

Input format There are
two lines of input, the first line contains the integer n.
The second line contains n integers (all integers are in the range of 1 to 109), which represents the entire number sequence.

Output format The
output is a row, containing n integers, indicating a sorted sequence of numbers.

Data range
1≤n≤100000

Input example:
5
3 1 2 4 5

Sample output:
1 2 3 4 5

Code:

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

const int N = 1e6 + 10;
int q[N],T[N];

void merge_sort(int *A, int L, int R, int *T){
    
    
	if(R-L > 1){
    
    
		int M = L + (R-L)/2;
		int l = L, m = M, i = L;
		
		merge_sort(A, L, M, T);
		merge_sort(A, M, R, T);	
		
		while(l<M || m<R){
    
    
			if(m>=R || (l<M && A[l]<=A[m]))
				T[i++] = A[l++];
			else
				T[i++] = A[m++];
		} 
		
		for(i=L; i<R; i++)	
			A[i] = T[i];
	}
}

int main(){
    
    
	int n;
	
    scanf("%d", &n);
    
    for (int i = 0; i < n; i++) 
		scanf("%d",&q[i]);
    
    merge_sort(q, 0, n, T);
    
    for (int i = 0; i < n; i++) 
		printf("%d ",q[i]);
    
    return 0;
} 

Guess you like

Origin blog.csdn.net/qq_44524918/article/details/108858364