1. Time complexity is the number of while, binary search O(h)=O(log2n)
2. Breadth-first traversal of nodes
function traverse(root){ const queue = [root]; while(queue.length){ const node = queue.shift(); printInfo(node); if(!node.children.length){ continue; } Array.from(node.children).forEach(x=>queue.push(x)); } } function printInfo(node){ console.log(node.nodeName, node.className) } traverse(root)
3. Depth-first traversal of the DOM tree
function printInfo(node, layer){ var str = '' for (let i = 1; i < layer; i++) { str += ' ' } console.log(`${layer}:${str}${node.tagName}.${node.className}`); } function dfs = (rootNodes, rootLayer) => { const roots = Array.from(rootNodes) while (roots.length) { const root = roots.shift(); printInfo (root, rootLayer); if (root.children.length) { dfs(root.children, rootLayer + 1) } } }
4. Bubble sort (O(n^2))
It repeatedly walks through the sequence to be sorted, comparing two elements at a time, and swapping them if they are in the wrong order. The work of visiting the sequence is repeated until no more exchanges are needed, that is, the sequence has been sorted.
function bubbleSort(arr){ const len = arr.length; for(let i = 0; i < len; i++){ for(let j = 0; j < len - 1 - i; j++){ if(arr[j] > arr[j + 1]){ [arr[j], arr[j+1]] = [arr[j+1], arr[j]]; } } } return arr; }
5. Quicksort (O(nlogn))
Divide the data to be sorted into two independent parts by one sorting, and all the data in one part is smaller than all the data in the other part, and then quickly sort the two parts of data according to this method. The whole sorting process can be Recursively, so that the entire data becomes an ordered sequence.
var quickSort = function(arr){ if(arr.length <= 1) {return arr;} const midIndex = Math.floor(arr.length / 2); const mid = arr.splice(midIndex, 1)[0]; const left = [], right = []; arr.forEach(function(item){ if(item < mid){ left.push(item); }else{ right.push(item); } }) return quickSort(left).concat([mid], quickSort(right)); }