算法学习杂记

一、二分

找最小值:

1、mid = (r - l) / 2 + 1

2、if(arr[mid] < arr[r] : r = mid (在左边)

   if(arr[mid] > arr[r] : l = mid + 1 (在右边)

   if(arr[mid] == arr[r] : r-- (缩小范围)

二、二叉树的遍历

前:根左右

preOrder(root){

  if(root){
    console.log(root.val)

    preOrder(root.left)

 

    preOrder(root.right)

  }

}

中:左根右

midOrder(root){

  if(root){

    preOrder(root.left)

    console.log(root.val)

    preOrder(root.right)

  }

}

后:左右根

lastOrder(root){

  if(root){

    preOrder(root.left)

    preOrder(root.right)

    console.log(root.val)

  }

}

三、二叉搜索树

1、若左子树不为空,所有节点小于根节点

2、若右子树不为空,所有节点大于根节点

3、中序遍历为从小到大的递增序列

四、快排 JS实现

function quickSort(arr){
    if(arr.length <= 1)
        return arr
    let base = arr.splice(Math.floor(arr.length / 2),1)
    let [left,right] = [[],[]]
    for(let i = 0; i < arr.length; i++){
        if (arr[i] < base){
            left.push(arr[i])
        }else {
            right.push(arr[i])
        }
    }
    return quickSort(left).concat(base, quickSort(right))
}
console.log(quickSort([5,4,3,2,1]))

 

posted @ 2021-05-08 22:37  小周不爱吃鱼  阅读(50)  评论(0)    收藏  举报