1. /**
    2. * 二分查找,也成为折半查找,每次都能将查找区间减半,时间复杂度为 O(logN)
    3. *
    4. * 中间值查找方式 Math.floor((l + h) / 2)
    5. *
    6. * 示例
    7. * Input : [1,2,3,4,5]
    8. * key : 3
    9. * return the index : 2
    10. **/
    11. function binarySearch(nums, target) {
    12. let l = 0,
    13. h = nums.length - 1;
    14. while (l <= h) {
    15. let m = Math.floor((l + h) / 2);
    16. if (nums[m] > target) {
    17. h = m ;
    18. } else if (nums[m] < target) {
    19. l = m + 1;
    20. } else {
    21. return m
    22. }
    23. }
    24. }