当前位置:网站首页>Sort merge sort
Sort merge sort
2022-07-03 22:37:00 【Up】
1. The basic idea
Merge sorting is an effective sorting algorithm based on merge operation . The algorithm is a divide-and-conquer method (Divide and Conquer) A very typical application . Merges ordered subsequences , You get a perfectly ordered sequence ; So let's make each subsequence in order , Then make the subsequence segments in order . If two ordered tables are merged into one ordered table , be called 2- Road merging .
2. Add : Divide and conquer method :
When solving an input scale of n, and n When there is a big problem in the value of , Direct solution is often very difficult . At this time , You can first analyze some characteristics of the problem itself , Then start from these characteristics , Choose some appropriate design strategies to solve . for example , If you put n Input is divided into k A subset of , Solve these subsets respectively , Then combine the obtained solutions , So we can get the solution of the whole problem , such , Sometimes you can get good results . This method , It's the so-called divide and conquer .
Generally speaking , Divide and conquer is to divide the problem into several sub problems to deal with . These sub questions , The structure is the same as the original problem , But it is smaller in scale than the original . If the obtained sub problem is relatively large , Divide and conquer strategies can be used repeatedly , Divide these sub problems into smaller ones 、 Subproblems with the same structure . such , You can use recursive methods to solve these sub problems respectively , And combine the solutions of these subproblems , So as to obtain the solution of the original problem .
3. Dynamic diagram demonstration 
4. Algorithm description
Put the length to n The input sequence of is divided into two lengths n/2 The subsequence ;
Merge and sort these two subsequences respectively ;
Merge two sorted subsequences into a final sorted sequence .
Pictured :

You can see that this structure is very similar to a complete two pronged tree , In this paper, we use recursion to implement merging and sorting ( It can also be implemented in an iterative way ). branch The stage can be understood as the process of recursively splitting the molecular sequence , The recursion depth is log2n.
Look again. cure Stage , We need to combine two ordered subsequences into an ordered sequence , For example, the last merge in the figure above , To put [4,5,7,8] and [1,2,3,6] Two ordered subsequences , Merge into final sequence [1,2,3,4,5,6,7,8], Let's take a look at the implementation steps .

package com.igeek.sort;
import java.util.Arrays;
public class MergeSort {
public static void main(String []args){
int []arr = {
9,8,7,6,5,4,3,2,1};
sort(arr);
System.out.println(Arrays.toString(arr));
}
public static void sort(int []arr){
int []temp = new int[arr.length];// Before sorting , First, create a temporary array whose length is equal to the length of the original array , Avoid frequent space creation in recursion
sort(arr,0,arr.length-1,temp);
}
private static void sort(int[] arr,int left,int right,int []temp){
if(left<right){
int mid = (left+right)/2;//
sort(arr,left,mid,temp);// Left merge sort , Make left subsequence ordered
sort(arr,mid+1,right,temp);// Merge and sort on the right , Make the right subsequence ordered
merge(arr,left,mid,right,temp);// Merge two ordered subarrays
}
}
private static void merge(int[] arr,int left,int mid,int right,int[] temp){
int i = left;// Left sequence pointer ( A pointer is a variable that holds the storage address of an object )->index;
int j = mid+1;// Right sequence pointer
int t = 0;// Temporary array pointer
while (i<=mid && j<=right){
if(arr[i]<=arr[j]){
temp[t++] = arr[i++];
}else {
temp[t++] = arr[j++];
}
}
while(i<=mid){
// Fill the remaining elements on the left with temp in
temp[t++] = arr[i++];
}
while(j<=right){
// Fill the remaining elements of the right sequence into temp in
temp[t++] = arr[j++];
}
t = 0;
// take temp Copy all the elements in to the original array
while(left <= right){
arr[left++] = temp[t++];
}
}
}
summary
Merge sort is stable sort , It's also a very efficient sort , Sorting that can take advantage of the full binary tree feature is generally not too bad .java in Arrays.sort() We have adopted a method called TimSort Sort algorithm , It's an optimized version of merge sort . As can be seen from the figure above , The average time complexity of each merge operation is O(n), The depth of a complete binary tree is 0 |log2n|. The total average time complexity is O(nlogn). and , The merge order is the best , The worst , The average time complexity is O(nlogn).
边栏推荐
- SDNU_ ACM_ ICPC_ 2022_ Winter_ Practice_ 4th [individual]
- User login function: simple but difficult
- On my first day at work, this API timeout optimization put me down!
- Pointer concept & character pointer & pointer array yyds dry inventory
- JS Demo calcule combien de jours il reste de l'année
- How can enterprises and developers take advantage of the explosion of cloud native landing?
- China HDI market production and marketing demand and investment forecast analysis report Ⓢ 2022 ~ 2028
- File copy method
- Buuctf, misc: n solutions
- Text replacement demo
猜你喜欢

Cesium terrain clipping draw polygon clipping

Format cluster and start cluster

1068. Consolidation of ring stones (ring, interval DP)

Leetcode: a single element in an ordered array

Redis single thread and multi thread

Bluebridge cup Guoxin Changtian single chip microcomputer -- detailed explanation of schematic diagram (IV)

JS closure knowledge points essence
![[actual combat record] record the whole process of the server being attacked (redis vulnerability)](/img/9c/34b916aca2f9270ec4cf4651f0de7e.jpg)
[actual combat record] record the whole process of the server being attacked (redis vulnerability)

2022 free examination questions for safety management personnel of hazardous chemical business units and reexamination examination for safety management personnel of hazardous chemical business units

QGIS grid processing DEM data reclassification
随机推荐
Data consistency between redis and database
Code in keil5 -- use the code formatting tool astyle (plug-in)
SDMU OJ#P19. Stock trading
Es6~es12 knowledge sorting and summary
STM32 multi serial port implementation of printf -- Based on cubemx
Team collaborative combat penetration tool CS artifact cobalt strike
2022 G3 boiler water treatment registration examination and G3 boiler water treatment examination papers
2022 safety officer-b certificate examination summary and safety officer-b certificate simulation test questions
Conditional statements of shell programming
JS closure knowledge points essence
Some 5000+ likes, the development notes of a director of cosmic factory, leaked
Codeforces Round #768 (Div. 1)(A-C)
2022 high altitude installation, maintenance and removal of examination question bank and high altitude installation, maintenance and removal of examination papers
How the computer flushes the local DNS cache
Report on the current situation and development trend of ethoxylated sodium alkyl sulfate industry in the world and China Ⓞ 2022 ~ 2027
2022 electrician (elementary) examination questions and electrician (elementary) registration examination
LeetCode 1647. Minimum deletion times of unique character frequency
Data consistency between redis and database
File copy method
Report on the development strategy of China's engineering bidding agency and suggestions for the 14th five year plan Ⓙ 2022 ~ 2028