An algorithm is just a function that converts the input of a certain data structure into the output of a certain data structure. The internal logic of the algorithm determines how to convert.
Basic Algorithm
1. Sorting
1. Bubble sorting
//冒泡排序function bubbleSort(arr) { for(var i = 1, len = arr.length; i < len - 1; ++i) { for(var j = 0; j <= len - i; ++j) { if (arr[j] > arr[j + 1]) { let temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } }
2. Insertion sorting
//插入排序 过程就像你拿到一副扑克牌然后对它排序一样 function insertionSort(arr) { var n = arr.length; // 我们认为arr[0]已经被排序,所以i从1开始 for (var i = 1; i < n; i++) { // 取出下一个新元素,在已排序的元素序列中从后向前扫描来与该新元素比较大小 for (var j = i - 1; j >= 0; j--) { if (arr[i] >= arr[j]) { // 若要从大到小排序,则将该行改为if (arr[i] <= arr[j])即可 // 如果新元素arr[i] 大于等于 已排序的元素序列的arr[j], // 则将arr[i]插入到arr[j]的下一位置,保持序列从小到大的顺序 arr.splice(j + 1, 0, arr.splice(i, 1)[0]); // 由于序列是从小到大并从后向前扫描的,所以不必再比较下标小于j的值比arr[j]小的值,退出循环 break; } else if (j === 0) { // arr[j]比已排序序列的元素都要小,将它插入到序列最前面 arr.splice(j, 0, arr.splice(i, 1)[0]); } } } return arr; }
When the goal is ascending sorting, the best case is that the sequence is already sorted in ascending order, then It only needs to be compared n-1 times, and the time complexity is O(n). The worst case scenario is that the sequence is originally sorted in descending order, so n(n-1)/2 times need to be compared, and the time complexity is O(n^2).
So on average, the time complexity of insertion sort is O(n^2). Obviously, the power-level time complexity means that insertion sort is not suitable for situations where there is a lot of data. Generally speaking, insertion sort is suitable for sorting small amounts of data.
3. Quick sort
//快速排序 function qSort(arr) { //声明并初始化左边的数组和右边的数组 var left = [], right = []; //使用数组第一个元素作为基准值 var base = arr[0]; //当数组长度只有1或者为空时,直接返回数组,不需要排序 if(arr.length <= 1) return arr; //进行遍历 for(var i = 1, len = arr.length; i < len; i++) { if(arr[i] <= base) { //如果小于基准值,push到左边的数组 left.push(arr[i]); } else { //如果大于基准值,push到右边的数组 right.push(arr[i]); } } //递归并且合并数组元素 return [...qSort(left), ...[base], ...qSort(right)]; //return qSort(left).concat([base], qSort(right));}
Supplement:
In this code, we can see that this The code realizes distinguishing the left and right parts through pivot, and then recursively continues pivot sorting on the left and right parts, realizing the text description of quick sorting. In other words, there is no problem in the implementation of this algorithm.
Although this implementation is very easy to understand. However, this implementation also has room for improvement. In this implementation, we found that two arrays, left/right, are defined within the function to store temporary data. As the number of recursions increases, more and more temporary data will be defined and stored, requiring Ω(n) additional storage space.
Therefore, like many algorithm introductions, the in-place partitioning version is used to implement quick sort. Let us first introduce what an in-place partitioning algorithm is.
Description of in-place partitioning algorithm
Pick out an element from the sequence, called "pivot" , the position of the first element of the array is used as the index.
Traverse the array. When the array number is less than or equal to the base value, exchange the number at the index position with the number and index 1
Exchange the base value with the current index position
After the above three steps, the base value will be centered, and the numbers on the left and right sides of the array will be smaller or larger than the base value respectively. . At this time, the sorted array can be obtained by recursively partitioning in place.
Implementation of in-place partitioning algorithm
// 交换数组元素位置 function swap(array, i, j) { var temp = array[i]; array[i] = array[j]; array[j] = temp; } function partition(array, left, right) { var index = left; var pivot = array[right]; // 取最后一个数字当做基准值,这样方便遍历 for (var i = left; i < right; i++) { if (array[i] <= pivot) { swap(array, index, i); index++; } } swap(array, right, index); return index; }
Because we need to recursively partition in-place multiple times, and at the same time, we do not want additional address space, so when implementing the partitioning algorithm There will be three parameters, namely the original array array, the starting point left of the array that needs to be traversed, and the end point of the array right that needs to be traversed.
Finally, a sorted index value is returned for the next recursion. The value corresponding to this index must be smaller than the array element on the left side of the index and larger than all the array elements on the right side.
Basically again, we can further optimize the partitioning algorithm. We found that
In-situ partition version is fast Sorting implementation
function quickSort(array) { function swap(array, i, j) { var temp = array[i]; array[i] = array[j]; array[j] = temp; } function partition(array, left, right) { var index = left; var pivot = array[right]; // 取最后一个数字当做基准值,这样方便遍历 for (var i = left; i < right; i++) { if (array[i] < pivot) { swap(array, index, i); index++; } } swap(array, right, index); return index; } function sort(array, left, right) { if (left > right) { return; } var storeIndex = partition(array, left, right); sort(array, left, storeIndex - 1); sort(array, storeIndex + 1, right); } sort(array, 0, array.length - 1); return array; }
2. String
1. Palindrome string
//判断回文字符串 function palindrome(str) { var reg = /[\W\_]/g; var str0 = str.toLowerCase().replace(reg, ""); var str1 = str0.split("").reverse().join(""); return str0 === str1; }
2. Flip the string
function reverseString(str) { return str.split("").reverse().join(""); }
3. The character that appears the most times in the string
function findMaxDuplicateChar(str) { var cnt = {}, //用来记录所有的字符的出现频次 c = ''; //用来记录最大频次的字符 for (var i = 0; i < str.length; i++) { var ci = str[i]; if (!cnt[ci]) { cnt[ci] = 1; } else { cnt[ci]++; } if (c == '' || cnt[ci] > cnt[c]) { c = ci; } } console.log(cnt) return c; }
3. Array
1. Array deduplication
//数组去重 function uniqueArray(arr) { var temp = []; for (var i = 0; i < arr.length; i++) { if (temp.indexOf(arr[i]) == -1) { temp.push(arr[i]); } } return temp; //or return Array.from(new Set(arr)); }
4. Search
1. Binary search
//二分查找 function binary_search(arr, l, r, v) { if (l > r) { return -1; } var m = parseInt((l + r) / 2); if (arr[m] == v) { return m; } else if (arr[m] < v) { return binary_search(arr, m+1, r, v); } else { return binary_search(arr, l, m-1, v); } }
Apply binary search to the previous insertion sort to form a binary insertion sort, which is said to improve efficiency. But when I tested, maybe the amount of data was too small, and I didn't find too obvious a gap. . You can try it yourself ~ (for example, use console.time('Insertion sorting takes time') and console.timeEnd('Insertion sorting takes time') at the beginning and end of the function call)
5. Tree search/traversal
1. Depth-first search
//深搜 非递归实现 function dfs(node) { var nodeList = []; if (node) { var stack = []; stack.push(node); while(stack.length != 0) { var item = stack.pop(); nodeList.push(item); var children = item.children; for (var i = children.length-1; i >= 0; i--) { stack.push(children[i]); } } } return nodeList; } //深搜 递归实现 function dfs(node, nodeList) { if (node) { nodeList.push(node); var children = node.children; for (var i = 0; i < children.length; i++) { dfs(children[i], nodeList); } } return nodeList; }
2. Breadth-first search
//广搜 非递归实现 function bfs(node) { var nodeList = []; if (node != null) { var queue = []; queue.unshift(node); while (queue.length != 0) { var item = queue.shift(); nodeList.push(item); var children = item.children; for (var i = 0; i < children.length; i++) queue.push(children[i]); } } return nodeList; } //广搜 递归实现 var i=0; //自增标识符 function bfs(node, nodeList) { if (node) { nodeList.push(node); if (nodeList.length > 1) { bfs(node.nextElementSibling, nodeList); //搜索当前元素的下一个兄弟元素 } node = nodeList[i++]; bfs(node.firstElementChild, nodeList); //该层元素节点遍历完了,去找下一层的节点遍历 } return nodeList; }
High-order function derivation algorithm
1. Filter deduplication
filter is also a commonly used operation, which is used Filter out certain elements of Array and return the remaining elements. It can also be understood this way. The callback function of filter processes each element of Array. If the processing result returns false, the filter result will remove the element. If true, it will remain.
Use the high-order function filter(). The key is It lies in correctly implementing a "filter" function.
In fact, this filtering function has multiple parameters, filter(function (element, index, self)), which demonstrates the use of filter to remove duplicates, like this:
var r, arr = ['apple', 'strawberry', 'banana', 'pear', 'apple', 'orange', 'orange', 'strawberry']; r = arr.filter(function (element, index, self) { return self.indexOf(element) === index; //拿到元素,判断他在数组里第一次出现的位置,是不是和当前位置一样, //一样的话返回true,不一样说明重复了,返回false。 });
2, sort sorting algorithm
排序也是在程序中经常用到的算法。无论使用冒泡排序还是快速排序,排序的核心是比较两个元素的大小。如果是数字,我们可以直接比较,但如果是字符串或者两个对象呢?
直接比较数学上的大小是没有意义的,因此,比较的过程必须通过函数抽象出来。通常规定,对于两个元素x和y,如果认为x y,则返回1,这样,排序算法就不用关心具体的比较过程,而是根据比较结果直接排序。
值得注意的例子:
// 看上去正常的结果: ['Google', 'Apple', 'Microsoft'].sort(); // ['Apple', 'Google', 'Microsoft']; // apple排在了最后: ['Google', 'apple', 'Microsoft'].sort(); // ['Google', 'Microsoft", 'apple'] // 无法理解的结果: [10, 20, 1, 2].sort(); // [1, 10, 2, 20]
解释原因
第二个排序把apple排在了最后,是因为字符串根据ASCII码进行排序,而小写字母a的ASCII码在大写字母之后。
第三个排序结果,简单的数字排序都能错。
这是因为Array的sort()方法默认把所有元素先转换为String再排序,结果’10’排在了’2’的前面,因为字符’1’比字符’2’的ASCII码小。
因此我们把结合这个原理:
var arr = [10, 20, 1, 2]; arr.sort(function (x, y) { if (x < y) { return -1; } if (x > y) { return 1; } return 0; }); console.log(arr); // [1, 2, 10, 20]
上面的代码解读一下:传入x,y,如果x
还有一个,sort()方法会直接对Array进行修改,它返回的结果仍是当前Array,一个例子:
var a1 = ['B', 'A', 'C'];var a2 = a1.sort(); a1; // ['A', 'B', 'C'] a2; // ['A', 'B', 'C'] a1 === a2; // true, a1和a2是同一对象
相关免费学习推荐:js视频教程
The above is the detailed content of Introduction to some common basic algorithms in JS. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
