Skip to content

Commit 40f240a

Browse files
authored
Merge pull request keon#753 from DivyanshMandhan/master
add ternary search
2 parents e48b9ac + ef63e53 commit 40f240a

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

algorithms/search/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from .binary_search import *
2+
from .ternary_search import *
23
from .first_occurrence import *
34
from .last_occurrence import *
45
from .linear_search import *
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
Ternary search is a divide and conquer algorithm that can be used to find an element in an array.
3+
It is similar to binary search where we divide the array into two parts but in this algorithm,
4+
we divide the given array into three parts and determine which has the key (searched element).
5+
We can divide the array into three parts by taking mid1 and mid2.
6+
Initially, l and r will be equal to 0 and n-1 respectively, where n is the length of the array.
7+
mid1 = l + (r-l)/3
8+
mid2 = r – (r-l)/3
9+
10+
Note: Array needs to be sorted to perform ternary search on it.
11+
T(N) = O(log3(N))
12+
log3 = log base 3
13+
"""
14+
def ternary_search(l, r, key, arr):
15+
while r >= l:
16+
17+
mid1 = l + (r-l) // 3
18+
mid2 = r - (r-l) // 3
19+
20+
if key == arr[mid1]:
21+
return mid1
22+
if key == mid2:
23+
return mid2
24+
25+
if key < arr[mid1]:
26+
# key lies between l and mid1
27+
r = mid1 - 1
28+
elif key > arr[mid2]:
29+
# key lies between mid2 and r
30+
l = mid2 + 1
31+
else:
32+
# key lies between mid1 and mid2
33+
l = mid1 + 1
34+
r = mid2 - 1
35+
36+
# key not found
37+
return -1

tests/test_search.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from algorithms.search import (
22
binary_search, binary_search_recur,
3+
ternary_search,
34
first_occurrence,
45
last_occurrence,
56
linear_search,
@@ -41,6 +42,15 @@ def test_binary_search(self):
4142
self.assertEqual(11, binary_search_recur(array, 0, 11, 6))
4243
self.assertEqual(-1, binary_search_recur(array, 0, 11, 7))
4344
self.assertEqual(-1, binary_search_recur(array, 0, 11, -1))
45+
46+
def test_ternary_search(self):
47+
array = [1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6]
48+
self.assertEqual(10, ternary_search(0, 11, 5, array))
49+
self.assertEqual(3, ternary_search(0, 10, 3, array))
50+
self.assertEqual(-1, ternary_search(0, 10, 5, array))
51+
self.assertEqual(-1, ternary_search(0, 11, 7, array))
52+
self.assertEqual(-1, ternary_search(0, 11, -1, array))
53+
4454

4555
def test_last_occurrence(self):
4656
array = [1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6, 6, 6]

0 commit comments

Comments
 (0)