From 46a7ae5db3f82c3a152c195983fb7e3bfb43f206 Mon Sep 17 00:00:00 2001 From: Fazil Akhtar Date: Sun, 3 Oct 2021 10:18:54 +0300 Subject: [PATCH] - added ternary search [Python] --- .../Python_Programs/ternary_search.py | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Program's_Contributed_By_Contributors/Python_Programs/ternary_search.py diff --git a/Program's_Contributed_By_Contributors/Python_Programs/ternary_search.py b/Program's_Contributed_By_Contributors/Python_Programs/ternary_search.py new file mode 100644 index 000000000..f92fdf81a --- /dev/null +++ b/Program's_Contributed_By_Contributors/Python_Programs/ternary_search.py @@ -0,0 +1,29 @@ +def ternary_search(arr, l, r, x): + if (r >= l): + mid1 = l + (r - l)//3 + mid2 = mid1 + (r - l)//3 + + if arr[mid1] == x: + return mid1 + + if arr[mid2] == x: + return mid2 + + if arr[mid1] > x: + return ternary_search(arr, l, mid1-1, x) + + if arr[mid2] < x: + return ternary_search(arr, mid2+1, r, x) + + return ternary_search(arr, mid1+1, mid2-1, x) + + return -1 + + +## Testing +arr = [2, 4, 6, 8, 3, 6, 9] +result = ternary_search(arr, 0, len(arr)-1, 3) +if result == -1: + print("Element is not present in array") +else: + print (f"Element is present at index: {result}")