신기술

검색 알고리즘

니엘개발자 2023. 12. 20. 14:09
반응형

코딩꿀팁: 검색 알고리즘

1. 이진 검색 알고리즘

이진 검색 알고리즘은 정렬된 배열에서 특정 값을 찾는 효율적인 방법입니다. 이 알고리즘의 핵심은 중간 값과 찾고자 하는 값의 비교를 통해 검색 범위를 반으로 줄여나가는 것입니다.

 function binarySearch(arr, target) { let low = 0; let high = arr.length - 1; while (low <= high) { const mid = Math.floor((low + high) / 2); if (arr[mid] === target) { return mid; } else if (arr[mid] < target) { low = mid + 1; } else { high = mid - 1; } } return -1; } const arr = [1, 2, 3, 4, 5]; const target = 3; const result = binarySearch(arr, target); console.log(`Target ${target} is found at index ${result}`); 

2. 해시 테이블을 이용한 검색 알고리즘

해시 테이블은 키와 값을 연결시켜 빠르게 값을 찾을 수 있는 자료구조입니다. 해시 함수를 이용하여 키를 고유의 인덱스에 매핑하고, 이 인덱스를 통해 값을 저장하고 검색합니다.

 class HashTable { constructor(size) { this.size = size; this.table = new Array(size); } hash(key) { let hash = 0; for (let i = 0; i < key.length; i++) { hash += key.charCodeAt(i); } return hash % this.size; } insert(key, value) { const index = this.hash(key); if (!this.table[index]) { this.table[index] = []; } this.table[index].push({ key, value }); } search(key) { const index = this.hash(key); if (this.table[index]) { for (let i = 0; i < this.table[index].length; i++) { if (this.table[index][i].key === key) { return this.table[index][i].value; } } } return null; } } const hashTable = new HashTable(10); hashTable.insert("apple", "사과"); hashTable.insert("banana", "바나나"); console.log(hashTable.search("apple")); // 출력: 사과 
반응형

'신기술' 카테고리의 다른 글

네트워크 프로그래밍  (0) 2023.12.20
알고리즘 디자인 패턴  (0) 2023.12.20
정렬 알고리즘  (1) 2023.12.20
자료 구조  (0) 2023.12.20
빅 오 표기법  (0) 2023.12.20