λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
Frontend/JavaScript

[ μžλ°”μŠ€ν¬λ¦½νŠΈ(JavaScript) ] 이진탐색(binarySearch) κ΅¬ν˜„λ°©λ²•

by YWTechIT 2021. 8. 8.
728x90

πŸ“ binarySearch(이진탐색)

μ •λ ¬λœ λ¦¬μŠ€νŠΈμ—μ„œ μ›ν•˜λŠ” ν•­λͺ©μ„ 찾기에 효율적인 μ•Œκ³ λ¦¬μ¦˜μ΄λ‹€. 이진 탐색을 κ°€μž₯ 많이 μ‚¬μš©ν•˜λŠ” κ²½μš°λŠ” λ°°μ—΄μ—μ„œ μ–΄λ–€ ν•­λͺ©μ„ μ°Ύμ•„μ•Ό ν•  λ•ŒμΈλ°, 예λ₯Ό λ“€μ–΄ 1 ~ 100κΉŒμ§€μ˜ λ²”μœ„μ—μ„œ 37μ΄λž€ 수λ₯Ό 찾으렀면 1λΆ€ν„° 100κΉŒμ§€ 1μ”© μ¦κ°€ν•˜λ©° μˆœμ„œλŒ€λ‘œ μ°ΎλŠ” 방법이 μžˆμ§€λ§Œ, νƒμƒ‰λ²”μœ„λ₯Ό 1/2μ”© μ€„μ΄λ©΄μ„œ μ°ΎλŠ” 방법이 μžˆλ‹€. μˆœμ„œλŒ€λ‘œ 찾을 λ•ŒλŠ” μ΅œμ•…μ˜ 경우 100λ²ˆμ„ μ°Ύμ•„μ•Ό ν•˜μ§€λ§Œ νƒμƒ‰λ²”μœ„λ₯Ό λ°˜μ”© 쀄여 μ°Ύμ•„κ°„λ‹€λ©΄ μ΅œλŒ€ 7번 λ§Œμ— μ›ν•˜λŠ” 값을 찾을 수 μžˆλ‹€. 이진 탐색을 μ½”λ“œλ‘œ κ΅¬ν˜„ν•˜λŠ” 방법은 λ‹€μŒκ³Ό κ°™λ‹€.

 

// while
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let target = 3;

function binarySearch(arr, target){
    let min = 0;
    let max = arr.length - 1;
    let cnt = 0;

    while (min <= max){
        cnt += 1;
        let mid = Math.floor((min + max) / 2);

        if (arr[mid] === target){
            return "found!", cnt;
        }else{
            if (arr[mid] < target){
                min = mid + 1;
            }else{
                max = mid - 1;
            }
        }
    }
    return "not found!";
}
728x90
// recursive
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let target = 3;

function binarySearch(start, end, arr, target){
    if (start > end){
        return "not found!";
    }

    let mid = Math.floor((min + max) / 2);

    if (arr[mid] === target){
        return "found!";
    }else{
        if (arr[mid] < target){
            binarySearch(mid + 1, end, arr, target);
        }else{
            binarySearch(start, mid - 1, arr, target);binarty
        }
    }
}

reference

  1. Khan Academy
λ°˜μ‘ν˜•

λŒ“κΈ€