Binary Search - 코딩테스트 with JS

컴클로딩·2022년 5월 2일
0

코딩테스트 with JS

목록 보기
3/3
post-thumbnail

Binary Search


📝 간단한 개념정리

  • 이진 탐색 : 배열 내부의 데이터가 정렬되어 있어야만 사용할 수 있는 알고리즘. 찾으려는 데이터와 중간점 위치에 있는 데이터를 반복적으로 비교해 원하는 데이터를 찾는 것이 이진 탐색 과정이다.

  • 시간복잡도 : O(logN)

  • Python으로 구현
def binary_search(arr, target):
    low, high = 0, len(arr) - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] > target:
            high = mid - 1
        if arr[mid] == target:
            return mid
        if arr[mid] < target:
            low = mid + 1
    return -1


arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "N", "O", "P"]
target = "G"

result = binary_search(arr, target)
print(result)
결과값
6

  • Javascript로 구현
function binary_search(arr, target){
    let low = 0,
        high = arr.length - 1;
    while(low <= high){
        let mid = parseInt((low + high) / 2); 
        if (arr[mid] > target){
            high = mid - 1;
        } if (arr[mid] === target){
            return mid;
        } if (arr[mid] < target) {
            low = mid + 1;
        }
    }
    return -1;
}


let arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "N", "O", "P"]
const target = "G"

let result = binary_search(arr, target)
console.log(result)
결과값
6

🤲🏻 차이점

  • 참고로 Python에는 bisect라는 라이브러리가 있어서 binary search를 쉽게 사용할 수 있다!

    • 참고코드
    from bisect import bisect_left, bisect_right
    
    		a = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "N", "O", "P"]
    		x = "G"
    
    		print(bisect_left(a, x))
    		print(bisect_right(a, x))
    결과값
    6
    7
  • while문, if문의 형태가 조금 다름.

참고자료

profile
어떠한 가치를 창출할 수 있을까를 고민하는 개발자. 주로 Spring으로 개발해요. https://comclothing.tistory.com/ 👈🏻티스토리 블로그로 이전 완료

0개의 댓글