JS review note 1: bubble sort and binary tree column

Time:2021-6-10

Here, I will gradually sort out some JS development knowledge and share it with you

1: Bubble sort

Usage scenario: sort the array as a whole according to the size of a value in the array

Difficulty: simple

Principle: first loop, loop to get all the values from the first to the penultimate range, judge the current value and the value of the next loop, if the conditions are met, directly replace in the loop, and then repeatedly call the method ontology

Case study:

var arr = [10,1,2,5,12,3,42,20]
        function arrleft(){
            var value='';
            for(var i=0;i

  

2: Binary tree column

Usage scenario: find the corresponding value in JSON with fixed specifications

Difficulty: difficulty

Principle: get all the children of JSON through multiple parsing calls

Case study:

Data template

        var json = {
            id:0,
            value:'0',
            left:{
                id:1,
                value:'a',
                left:{
                    id:2,
                    value:'b',
                    left:{
                        id:3,
                        value:'c',
                    },
                    right:{
                        id:4,
                        value:'d',
                        left:{
                            id:5,
                            value:'e'
                        }
                    }
                },
                right:{
                    id:6,
                    value:'f',
                    right:{
                        id:7,
                        value:'g'
                    }
                }
            },
            right:{
                id:8,
                value:'h',
                left:{
                    id:9,
                    value:'I',
                    right:{
                        id:10,
                        value:'J',
                        left:{
                            id:11,
                            value:'K'
                        }
                    }
                },
                right:{
                    id:11,
                    value:'L'
                }
            }
        }

  

method

var i=0;
        function jsonFun(json,name){
            i++;
            if(json.id == name){
                console.log(json);
            }else{
                console.log(json.value);// Preorder traversal 
                if(json.left){
                    jsonFun(json.left,name)
                }
                console.log(json.value);// Middle order traversal
                if(json.right){
                    jsonFun(json.right,name)
                }
                console.log(json.value);// Postorder traversal
            }
        }
        jsonFun(json,1);
        console.log(i);// Number of cycles