Skip to content

Commit dfb7b44

Browse files
committed
Ternary search algorithm to locate a value in an array
1 parent 0ac53fb commit dfb7b44

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

‎SearchAlgorithms/ternarySearch.js‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
let ternarySearch = (arr, start, end, key) => {
2+
3+
if (start >= end) {
4+
return -1;
5+
}
6+
7+
let midFirst = start + Math.floor((end - start) / 3);
8+
let midSecond = midFirst + Math.floor((end - start) / 3);
9+
10+
if (arr[midFirst] === key) {
11+
return midFirst;
12+
}
13+
if (arr[midSecond] === key) {
14+
return midSecond;
15+
}
16+
17+
if (key < arr[midFirst]) {
18+
return ternarySearch(arr, start, midFirst - 1, key);
19+
}
20+
21+
if (key > arr[midSecond]) {
22+
return ternarySearch(arr, midFirst + 1, end, key);
23+
}
24+
25+
else {
26+
return ternarySearch(arr, midFirst + 1, midSecond - 1, key);
27+
}
28+
};
29+
30+
const arr = [1,6,9,17,21,69,85,100];
31+
console.log(ternarySearch(arr, 0, arr.length, 1));

0 commit comments

Comments
 (0)