본문 바로가기
CS (컴퓨터 사이언스)/Algorithm (알고리즘)

[알고리즘] section7 정렬과 그리디, 결정알고리즘 - 이분탐색

by dreamer10457 2024. 5. 14.
반응형

알고리즘 - 이분검색(binary search)

 

<html>
  <head>
    <meta charset="UTF-8" />
    <title>출력결과</title>
  </head>
  <body>
    <script>
      function solution(target, arr) {
        let answer;

        arr.sort((a, b) => a - b);

        let start = 0;
        let end = arr.length - 1;

        while (start <= end) {
          let mid = Math.floor((end + start) / 2);

          if (arr[mid] === target) {
            answer = mid + 1;
          } else if (arr[mid] < target) {
            start = mid + 1;
          } else {
            end = mid - 1;
          }
        }

        return answer;
      }

      let arr = [23, 87, 65, 12, 57, 32, 99, 81];
      console.log(solution(32, arr));
    </script>
  </body>
</html>

 

 

https://leeseong010.tistory.com/104

반응형