当前位置:网站首页>JS implementation of graphic merging and sorting process [source code attached]
JS implementation of graphic merging and sorting process [source code attached]
2022-06-11 06:36:00 【__ LeoZhang】
Introduce
Merge sort is a sort of sort worth learning in many sorts , In terms of time complexity, he can guarantee that O(nlogn) It's a stable sort , And his sorting using divide and conquer idea is very good , Here we can first introduce the general idea of merging and sorting .
Ideas
The idea of merging and sorting is called divide and conquer , in other words , Decomposition before treatment . So merge sort first uses the idea of similar bisection to split the array layer by layer , The splitting process does not perform sorting . When it is decomposed to the minimum cell, the adjacent elements in the minimum cell are compared and summarized into a new array layer by layer , Finally, merge to the original array . In other words, merge sort needs to create temporary extra space to handle each data merge during the sorting process . His idea is to split it into the smallest unit first , Finally, the smallest cells are merged into n An ordered array , Then merge the two ordered arrays into a new ordered array .
The illustration
Let's first introduce the process of splitting in the idea of partition and rule with a diagram . Because the idea is similar to binary search , So the first step is to find the middle value in the array , Because there may be odd and even differences, our middle position is not an absolute median , So here we use Math.floor((0,arr.length-1)/2) To determine the intermediate value , This time, we still take the last array data as an example
let arr = [13,2,7,21,8,65,2,0,1,9,14,7,63]Here we deliberately use the odd length array as an example to see the decomposition process . Please refer to the following figure. :

The above is the dichotomy based on the intermediate value we just described , Further decomposition to a single element , We will exchange and merge the grouped individual elements layer by layer from bottom to top .
First, we will sort and exchange the elements in the same group at the lowest level and return to the penultimate layer , Then continue to merge up layer by layer, as shown in the following figure .

The above figure has vividly described the merging idea of merging and sorting , We can see from the picture that except for the bottom node exchange , When bubbling up layer by layer, we can also see that these are two ordered arrays for sorting , So we can quickly build a new ordered array , Until the last merge, only two arrays are left to merge .
Code implementation
// Define an array
let arr = [13,2,7,21,8,65,2,0,1,9,14,7,63]
// Output the original array
console.log(arr)
/**
* The actual function of sorting
* @param {Object} arr Target array
* @param {Object} left The starting position
* @param {Object} right Termination position
* @param {Object} temp Temporary array
*/
function sortMerge(arr,left,right,temp){
// If the start position is smaller than the end position, the sorting logic is enabled
if(left<right){
// Determine the median , Divide the array into two parts
let mid = Math.floor((left+right)/2)
// Recursively perform the decomposition of the left part
sortMerge(arr,left,mid,temp)
// Recursively perform the decomposition of the right part
sortMerge(arr,mid+1,right,temp)
// After decomposition, merge from the last level of recursion
// Define the starting point of the array comparison in the left part
let l = left
// Define the starting point of the right array comparison
let r = mid+1
// Define the starting point of the temporary array
let k = 0
// When either the left array or the right array is not finished , Because decomposition may
// The left and right arrays are different in length
while(l<=mid&&r<=right){
// Determine which element to put in the array first , Move the temporary array pointer
// And move the pointer of the array to be compared
if(arr[l]>=arr[r]){
temp[k] = arr[r]
r++
k++
}else{
temp[k] = arr[l]
l++
k++
}
}
// When the above loop jumps out, it means that at least one array has come to the end
// Compare whether the left array has reached the destination , If not, continue to value the temporary array
while(l<=mid){
temp[k] = arr[l]
l++
k++
}
// Compare whether the right array has reached the end point. If not, continue to value the temporary array
while(r<=right){
temp[k] = arr[r]
r++
k++
}
// Remake temporary array pointer
k = 0
// Put the sorting result of the temporary array into the original array from the merged length range
while(left<=right){
arr[left] = temp[k]
left++
k++
}
// Output the sorting result
console.log(arr)
}
}
/**
* A function that performs sorting
* @param {Object} arr Array
*/
function sort(arr){
let left = 0
let right = arr.length-1
let temp = []
sortMerge(arr,left,right,temp)
}
sort(arr)The above is the actual js The code implementation of sorting logic , Here we can output the results of each sorting process to have a deeper understanding of the picture process .

summary
In this issue, we learn the idea of merging and sorting , Here we find that it overlaps with the ideas of heap sort and quick sort , Both use the idea of data structure , But the implementation is different , For the commonly used algorithms in programming, as long as we understand the idea of diagrams, the implementation for developers is just the difficulty of reading pictures and writing words , So don't complicate them or recite them . This sharing is over , I look forward to meeting you in the next sharing .
边栏推荐
- Resolve typeerror: ctx injections. tableRoot.$ scopedSlots[ctx.props.column.slot] is not a function
- 搜狐员工遭遇工资补助诈骗 黑产与灰产有何区别 又要如何溯源?
- Learn C language well from keywords
- The nearest common ancestor of 235 binary search tree
- Chapter 1 of machine learning [series] linear regression model
- Wechat applet (authorized login of TP5)
- The difference between call and apply and bind
- UEFI查找PCI设备
- Make a small game with R language and only basic package
- Scripy web crawler series tutorials (I) | construction of scripy crawler framework development environment
猜你喜欢

ERROR 1215 (HY000): Cannot add foreign key constraint
![Handwritten promise [04] - then method chain call to recognize promise object self return](/img/3e/2bf97b2e151dae3b9681fb0ce77d2f.jpg)
Handwritten promise [04] - then method chain call to recognize promise object self return

Why don't we have our own programming language?

572. 另一个树的子树

Résoudre le problème de la durée inexacte du fichier audio AAC obtenu par ffmpeg

autojs,读取一行删除一行,停止自己外的脚本

Who is stronger, zip or 7-Zip, and how to choose?
![Chapter 1 of machine learning [series] linear regression model](/img/e2/1f092d409cb57130125b0d59c8fd27.jpg)
Chapter 1 of machine learning [series] linear regression model

Simple knapsack problem
![Handwritten promise [05] - exception capture of promise method and optional parameters of then method implementation](/img/e7/87069f921ae003511e32b23653703c.jpg)
Handwritten promise [05] - exception capture of promise method and optional parameters of then method implementation
随机推荐
The classification effect of converting video classification data set to picture classification data set on vgg16
FPGA interview notes (IV) -- sequence detector, gray code in cross clock domain, ping-pong operation, static and dynamic loss reduction, fixed-point lossless error, recovery time and removal time
FPGA interview notes (III) -- implementation of handshake signal synchronization in cross clock domain, arbitrary frequency division, binary conversion, RAM memory, original code inversion and complem
学好C语言从关键字开始
FPGA面试题目笔记(一)——FPGA开发流程、亚稳态和竞争冒险、建立保持时间、异步FIFO深度等
CCF 2013 12-4 interesting numbers
Eureka集群搭建
Mediaextractor source code analysis of multimedia framework analysis (1)
022 basic introduction to redis database 0
QT socket设置连接超时时间
Exchange two values without introducing the third variable
Shandong University machine learning experiment 5 SVM
Use meshlab to sample the point cloud of CAD model and display it in PCL
不引入第三个变量,交换两个值
Differences between FindIndex and indexof
socket. IO cross domain stepping pit
Moment time plug-in tips -js (super detailed)
Docker安装Mysql、Redis
修复鼠标右键没有vscode快捷入口的问题
必读1:格局越大的人,越懂得说话