From 7447a9f9c7bdef4ceef3a93cee110525f683927d Mon Sep 17 00:00:00 2001 From: Uday Patel Date: Mon, 9 Oct 2017 03:19:39 +0100 Subject: [PATCH] Added Ternary Search Algorithm --- searches/ternary_search.py | 112 +++++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 searches/ternary_search.py diff --git a/searches/ternary_search.py b/searches/ternary_search.py new file mode 100644 index 000000000..3b1c75314 --- /dev/null +++ b/searches/ternary_search.py @@ -0,0 +1,112 @@ +''' +This is a type of divide and conquer algorithm which divides the search space into +3 parts and finds the target value based on the property of the array or list +(usually monotonic property). + +Time Complexity : O(log3 N) +Space Complexity : O(1) +''' + +import sys + +# This is the precision for this function which can be altered. +# It is recommended for users to keep this number greater than or equal to 10. +precision = 10 + +# This is the linear search that will occur after the search space has become smaller. +def lin_search(left, right, A, target): + for i in range(left, right+1): + if(A[i] == target): + return i + +# This is the iterative method of the ternary search algorithm. +def ite_ternary_search(A, target): + left = 0 + right = len(A) - 1; + while(True): + if(left