Skip to content

Commit b8cc5e3

Browse files
committed
Added implementation of ternary search
1 parent 8794c85 commit b8cc5e3

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

pygorithm/searching/__init__.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,19 @@
44
from . import binary_search
55
from . import breadth_first_search
66
from . import depth_first_search
7+
from . import exponential_search
78
from . import interpolation_search
89
from . import linear_search
910
from . import quick_select
11+
from . import ternary_search
1012

1113
__all__ = [
1214
'binary_search',
1315
'breadth_first_search',
1416
'depth_first_search',
17+
'exponential_search',
1518
'interpolation_search',
1619
'linear_search',
17-
'quick_select'
20+
'quick_select',
21+
'ternary_search'
1822
]

pygorithm/searching/ternary_search.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
'''
2+
Author: OMKAR PATHAK
3+
Created at: 26th August 2017
4+
5+
Time complexity: O(logn)
6+
7+
More Info: https://en.wikipedia.org/wiki/Ternary_search
8+
'''
9+
from __future__ import division
10+
import inspect
11+
12+
def search(_list, left, right, target):
13+
if right >= left:
14+
mid1 = (left + right) // 3
15+
mid2 = (mid1 + right) // 3
16+
17+
# if target is present at mid1
18+
if _list[mid1] == target:
19+
return mid1
20+
21+
# if target is present at mid2
22+
if _list[mid2] == target:
23+
return mid2
24+
25+
# if target is present at left one-third
26+
if _list[mid1] > target:
27+
return search(_list, left, mid1 - 1, target)
28+
29+
# if target is present at right one-third
30+
if _list[mid2] < target:
31+
return search(_list, mid2 + 1, right, target)
32+
33+
# if target is present in the middle one-third
34+
return search(_list, mid1 + 1, mid2 - 1, target)
35+
36+
return False
37+
38+
def time_complexities():
39+
"""
40+
Return information on functions
41+
time complexity
42+
:return: string
43+
"""
44+
return "Time complexity: O(logn)"
45+
46+
47+
def get_code():
48+
"""
49+
easily retrieve the source code
50+
of the function
51+
:return: source code
52+
"""
53+
return inspect.getsource(search)

0 commit comments

Comments
 (0)