Bubble sort and binary search

Bubbling sorting: compare the element and the elements behind the element one by one, and put the larger ones in the back.
code show as below:

 function sort(arr){
            for(let i=0;i<arr.length-1;i++){
                for(let j=0;j<arr.length-(i+1);j++){
                    if(arr[j]>arr[j+1]){
                        let temp=arr[j]
                        arr[j]=arr[j+1]
                        arr[j+1]=temp
                    }
                }
            }
            return arr;
        }

Dichotomy search: Take a middle size and the left side and compare the right side respectively. If it happens to be equal to the value to be searched, return directly, otherwise if it is less than the middle value, search on the left, and search on the right if it is greater than the middle value. Do the cycle in turn. Until found.
code show as below:

  function binarySearch(arr,key){
            let h=arr.length-1
            let l=0
            while(l<=h){
                let m=Math.floor((h+1)/2)
                if(key===arr[m]){
                    return m;
                }else if(key>arr[m]){
                    return l=m+1
                }else if(key<arr[m]){
                    return h=m-1
                }
            }  
            return false
        }

Guess you like

Origin blog.csdn.net/weixin_44494811/article/details/108363008