What is merge sort
To understand a concept first, there is a design idea in the algorithm called divide and conquer .
In computer science, divide and conquer is a very important algorithm. The literal explanation is "divide and conquer", that is, divide a complex problem into two or more identical or similar sub-problems, and then divide the sub-problems into smaller sub-problems... until the final sub-problems can be solved simply and directly , The solution of the original problem is the combination of the solutions of the sub-problems. This technique is the basis of many efficient algorithms, such as sorting algorithms (quick sort, merge sort), Fourier transform (fast Fourier transform)...
Algorithm ideas
Merge sort is
- Decompose the sequence of n elements to be sorted into two subsequences with n/2 elements each
- Recursively do the same operation for two subsequences
- Merge two subsequences that have been sorted
The third step can be split into a single question to see if a subject leetcode merging two ordered arrays
Algorithm process
The merge sort process in the introduction to the algorithm is shown in the figure below
The process of merging = merging two ordered arrays. In the
introduction to the algorithm, the sentry needs to be used in the exercises after class. The sentry needs to be removed. So the following code does not use sentinels.
Double pointer
As shown in the example below
Implementation
javascript version
//分解 递归
function mergeSort(arr) {
let len = arr.length
if (len < 2) return arr
let middle = Math.floor(len / 2)
let left = arr.slice(0, middle)
let right = arr.slice(middle)
return merge(mergeSort(left), mergeSort(right))
}
//合并
function merge(left, right) {
let result = []
let i = 0
let j = 0
while ((i <= left.length - 1) && (j <= right.length - 1)) {
if (left[i] <= right[j]) {
result.push(left[i])
i = i + 1
} else {
result.push(right[j])
j = j + 1
}
}
while (i <= left.length - 1) {
result.push(left[i])
i = i + 1
}
while (j <= right.length - 1) {
result.push(right[j])
j = j + 1
}
return result
}