Algorithm
이진탐색 알고리즘(Binary Search Algorithm)
D.Y
2019. 10. 17. 12:46
반응형
안녕하세요.
오늘은 이진탐색 알고리즘에 대해서 알아보도록 하겠습니다.
이진탐색 알고리즘(Binary Search Algorithm)
- 1회 비교를 거칠때마다 탐색 범위가 대략 절반으로 줄어들기 때문에 이진탐색이라고 불린다.
- 배열의 값들이 정렬되어 있을때만 사용이 가능합니다.
function solution(element, some_list) {
let firstIndex = 0;
let lastIndex = some_list.length - 1;
while(firstIndex <= lastIndex) {
let centerIndex = Math.floor((firstIndex + lastIndex) / 2);
if (element === some_list[centerIndex]) {
return centerIndex;
}
else if (element < some_list[centerIndex]) {
lastIndex = centerIndex - 1;
}
else {
firstIndex = centerIndex + 1;
}
}
return "None";
}
console.log('solution: ', solution(2, [2, 3, 5, 7, 11])); // solution: 0
모두 즐거운 코딩 하세요~
반응형