정렬 되어있는 요소들을 반씩 제외하며 찾는 알고리즘
O(log N)만큼 시간복잡도가 걸린다.
ex) Up & Down 게임
이진 탐색 트리 문제점
- 최악의 경우 한쪽으로 편향된 트리가 될 수 있다.
ex) 5,4,3,2,1 순으로 추가할 때
const array = [null, 1, 2, 5, 125, 400, 777, 1004, 4563, 7777];
function arrayBinarySearch(array, findValue) {
let left = 0;
let right = array.length - 1;
let mid = Math.floor((left + right) / 2);
while (left < right) {
if (array[mid] === findValue) {
return mid;
}
if (array[mid] < findValue) {
left = mid + 1;
} else {
right = mid - 1;
}
mid = Math.floor((left + right) / 2);
}
return -1;
}
console.log(arrayBinarySearch(array, 1));
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BinarySearch {
constructor() {
this.root = null;
}
insert(value) {
const newNode = new Node(value);
if (this.root === null) {
this.root = newNode;
return;
}
let currentNode = this.root;
while (currentNode !== null) {
if (currentNode.value < value) {
if (currentNode.right === null) {
currentNode.right = newNode;
break;
}
currentNode = currentNode.right;
} else {
if (currentNode.left === null) {
currentNode.left = newNode;
break;
}
currentNode = currentNode.left;
}
}
}
has(value) {
let currentNode = this.root;
while (currentNode !== null) {
if (currentNode.value === value) {
return true;
}
if (currentNode.value < value) {
currentNode = currentNode.right;
} else {
currentNode = currentNode.left;
}
}
return false;
}
}
const tree = new BinarySearch();
tree.insert(5);
tree.insert(3);
tree.insert(7);
tree.insert(1);
console.log(tree.has(3)); // true
console.log(tree.has(2)); // false
프로그래머스 데브코스 교육 내용을 바탕으로 정리한 글 입니다.