Skip to content
This repository was archived by the owner on Nov 6, 2018. It is now read-only.

Commit 6c0fba4

Browse files
committed
Add ternary search and tests for it
1 parent 939c1ae commit 6c0fba4

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed
+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
"""
2+
Ternary search
3+
---------------
4+
Finds the maximum of unimodal function fn() within [left, right]
5+
To find the minimum, revert the if/else statement or revert the comparison.
6+
7+
Time Complexity: O(log(n))
8+
9+
"""
10+
11+
12+
def search(fn, left, right, precision):
13+
while abs(right - left) > precision:
14+
left_third = left + (right - left) / 3
15+
right_third = right - (right - left) / 3
16+
17+
if fn(left_third) < fn(right_third):
18+
left = left_third
19+
else:
20+
right = right_third
21+
22+
return (left + right) / 2

docs/searching.rst

+5
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,8 @@ Searching
2525
:members:
2626
:undoc-members:
2727
:show-inheritance:
28+
29+
.. automodule:: algorithms.searching.ternary_search
30+
:members:
31+
:undoc-members:
32+
:show-inheritance:

tests/test_searching.py

+18-1
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
""" Unit Tests for searching """
22
import unittest
3+
import math
34

45
from algorithms.searching import (
56
binary_search,
67
bmh_search,
78
breadth_first_search,
89
depth_first_search,
910
kmp_search,
10-
rabinkarp_search
11+
rabinkarp_search,
12+
ternary_search
1113
)
1214

1315

@@ -188,3 +190,18 @@ def test_rabinkarpsearch(self):
188190
rv2 = rabinkarp_search.search(self.string, "BCA")
189191
self.assertIs(rv1[0], 12)
190192
self.assertFalse(rv2)
193+
194+
195+
class TestTernarySearch(unittest.TestCase):
196+
"""
197+
Tests teranry search algorithm on unimodal functions
198+
"""
199+
200+
def test_terarysearch(self):
201+
self.function1 = lambda x: -(x - 2) ** 2
202+
self.function2 = lambda x: math.cos(x)
203+
self.eps = 1e-6
204+
rv1 = ternary_search.search(self.function1, -2.0, 2.0, self.eps)
205+
rv2 = ternary_search.search(self.function2, -2.0, 2.0, self.eps)
206+
self.assertAlmostEqual(rv1, 2.0, 6)
207+
self.assertAlmostEqual(rv2, 0.0, 6)

0 commit comments

Comments
 (0)