Notes on common sorting algorithms in JavaScript

::::::: 2020-11-06 01:22:50
notes common sorting algorithms javascript


Sorting algorithm is mainly for arrays , therefore , Before you start to learn , We first create a new data structure to facilitate our study .

function ArrayData () {
let ret = []
this.times = 0 // Count the execution times
this.push = (item) => {
ret.push(item)
}
this.toString = () => {
return ret.join()
}
}
const arr = [34, 11, 45, 22, 31, 99, 68, 54]

Bubble sort

Compare the size of two adjacent numbers , If the number in front is greater than that in the back , Then exchange the positions of these two numbers . To sort n A digital , Need experience n-1 Ergodic times .

According to the literal requirement , The code we wrote is like this

function ArrayData () {
// ......
this.bubbleSort = function () {
let length = ret.length;
for (let i = 0; i < length; i++) {
for (let j = 0; j < length - 1; j++) {
this.times++
if (ret[j] > ret[j + 1]) {
[ret[j], ret[j + 1]] = [ret[j + 1], ret[j]]
}
}
}
}
}
let tmp = new ArrayData()
arr.forEach((item) => {
tmp.push(item)
})
tmp.bubbleSort()
console.log(tmp.times) // 56

Obviously, this simple and crude sorting method has a lot of room for improvement , such as , We can detect every sort , If the sequence has been arranged successfully , There's no need to execute the following loop .

function ArrayData () {
// ......
this.bubbleSort = function () {
let length = ret.length;
for (let i = 0; i < length; i++) {
let change = false
for (let j = 0; j < length - 1; j++) {
this.times++Ï
if (ret[j] > ret[j + 1]) {
[ret[j], ret[j + 1]] = [ret[j + 1], ret[j]]
change = true
}
}
if (!change) {
break
}
}
}
}
let tmp = new ArrayData()
arr.forEach((item) => {
tmp.push(item)
})
tmp.bubbleSort()
console.log(tmp.times) // 21

In fact, there is still room for optimization . for instance , Let's say it's a total of 8 Number , The first cycle , It's going to bubble the largest number 8 position , The second cycle , It puts the second largest number in the list 7 position , therefore , There's no need to think about the last one in this cycle . Empathy , The next cycle doesn't need to consider the last two . The improved code is as follows :

function ArrayData () {
// ......
this.bubbleSort = function () {
let length = ret.length;
for (let i = 0; i < length; i++) {
let change = false
for (let j = 0; j < length - 1 - i; j++) {
this.times++
if (ret[j] > ret[j + 1]) {
[ret[j], ret[j + 1]] = [ret[j + 1], ret[j]]
change = true
}
}
if (!change) {
break
}
}
}
}
let tmp = new ArrayData()
arr.forEach((item) => {
tmp.push(item)
})
tmp.bubbleSort()
console.log(tmp.times) // 18

Selection sort

Traversal array , Find the smallest number in the first place , The second cycle finds the second smallest number and places it in the second place , And so on .

function ArrayData () {
// ......
this.selectionSort = function () {
let length = ret.length
for (let i = 0; i < length - 1; i++) {
let minIndex = i
for (let j = i; j < length; j++) {
if (ret[j] < ret[minIndex]) {
minIndex = j
}
}
if (i !== minIndex) {
[ret[i], ret[minIndex]] = [ret[minIndex], ret[i]]
}
}
}
}
let tmp = new ArrayData()
arr.forEach((item) => {
tmp.push(item)
})
tmp.selectionSort()

Insertion sort

Divide the array into two parts , The first part is ordered , Then insert the last part of the number into the array in front of the order . therefore , In the beginning, set the first element as the ordered part , Insert the following numbers separately .

function ArrayData () {
// ......
this.insertSort = function () {
let length = ret.length
let j
for (let i = 1; i < length; i++) {
let currentNumber = ret[i]
for (j = i - 1; j >= 0 && ret[j] > currentNumber; j--) {
ret[j + 1] = ret[j]
}
ret[j + 1] = currentNumber
}
}
}
let tmp = new ArrayData()
arr.forEach((item) => {
tmp.push(item)
})
tmp.insertSort()

Quick sort

Choose a number as the base number , Ergodic sequence , Compare it Put it in front of him , Put the smaller one behind him , And then recurs the above operation to the sequence before and after the reference number , Until the length of the sequence is 1.

function ArrayData () {
// ......
this.quickSort = function () {
quick(ret, 0, ret.length - 1);
function quick(array, left, right) {
let index
if (array.length > 1) {
index = partition(array, left, right)
if (left < index - 1) {
quick(array, left, index - 1)
}
if (right > index) {
quick(array, index, right)
}
}
return array
}
function partition(array, left, right) {
let pivot = array[Math.floor((right + left) / 2)],
i = left,
j = right;
while (i <= j) {
while (array[i] < pivot) {
i++
}
while (array[j] > pivot) {
j--
}
if (i <= j) {
swap(array, i, j);
i++;
j--;
}
}
return i
}
function swap(array, i, j) {
[array[i], array[j]] = [array[j], array[i]]
}
}
}
let tmp = new ArrayData()
arr.forEach((item) => {
tmp.push(item)
})
tmp.quickSort()

Quick sort in one sentence . Select the first element as the reference element , utilize filter Divide the array into two arrays larger than the reference element and smaller than the reference element , And the two arrays recursively call the fast sorting function .

function quickSort(arr) {
return arr.length <= 1 ? arr : quickSort(arr.slice(1).filter((item) => item <= arr[0])).concat(arr[0], quickSort(arr.slice(1).filter((item) => item > arr[0])))
}

Shell Sort

Hill sort is the grouping of arrays by a certain increment of the subscript , Insert rows into each group , As the increments decrease , Each array has more and more length , When the increment is reduced to 1 when , The whole document is just a group , The algorithm terminates .

function ArrayData () {
// ......
this.shellSort = function () {
let length = ret.length
for (let step = Math.floor(length / 2); step > 0; step = Math.floor(step / 2)) {
for (let i = 0; i < step; i++) {
shellInsertSort(i, step)
}
}
function shellInsertSort(index, step) {
let length = ret.length
let j
for (let i = index; i < length; i += step) {
let currentNumber = ret[i]
for (j = i - step; j >= 0 && ret[j] > currentNumber; j -= step) {
ret[j + step] = ret[j]
}
ret[j + step] = currentNumber
}
}
}
}
let tmp = new ArrayData()
arr.forEach((item) => {
tmp.push(item)
})
tmp.shellSort()

Merge sort

Merging and sorting adopts the idea of divide and rule , Merges ordered subsequences , You get a perfectly ordered sequence . So we split the sequence into an array of no more than two elements , And then merge it .

function ArrayData () {
// ......
this.mergeSort = function () {
ret = mergeSortFun(ret)
function mergeSortFun(arr) {
let length = arr.length
if (length <= 1) {
return arr
}
let mid = Math.floor(length / 2),
left = arr.slice(0, mid),
right = arr.slice(mid, length)
return mengeConnect(mergeSortFun(left), mergeSortFun(right))
}
function mengeConnect(left, right) {
let
leftIndex = 0,
rightIndex = 0,
result = []
while (leftIndex < left.length && rightIndex < right.length) {
result.push(left[leftIndex] < right[rightIndex] ? left[leftIndex++] : right[rightIndex++])
}
while (leftIndex < left.length) {
result.push(left[leftIndex++])
}
while (rightIndex < right.length) {
result.push(right[rightIndex++])
}
return result
}
}
}
let tmp = new ArrayData()
arr.forEach((item) => {
tmp.push(item)
})
tmp.mergeSort()

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[:::::::]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云