{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "def ternarySearch(target, nums, left, right):\n", "\n", " if left > right:\n", " return -1\n", "\n", " mid1 = left + (right-left+1) // 3\n", " mid2 = right - (right-left+1) // 3\n", "\n", " if nums[mid1] == target:\n", " return mid1\n", "\n", " if nums[mid2] == target:\n", " return mid2\n", "\n", " if target > nums[mid1]:\n", " # target must be on the left segment\n", " return ternarySearch(target,nums,left,mid1-1)\n", "\n", " if target < nums[mid1] and target > nums[mid2]:\n", " # target must be on the middle segment\n", " return ternarySearch(target,nums,mid1+1,mid2-1)\n", "\n", " # target must be on the right segment\n", " return ternarySearch(target,nums,mid2+1,right)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6\n", "-1\n", "54\n", "-1\n" ] } ], "source": [ "def main():\n", " nums = [443,339,333,231,202,17,11,9,8,7,6,5,4,1]\n", " for target in [11,111]:\n", " print(ternarySearch(target,nums,0,len(nums)-1)) # should print 6 and -1\n", "\n", " nums = [10*i for i in range(100,0,-1)]\n", " for target in [460,466]:\n", " print(ternarySearch(target,nums,0,len(nums)-1)) # should print 54 and -1\n", "\n", "main()" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "def ternarySearch(target, nums, left, right):\n", "\n", " if left > right:\n", " return -1\n", " \n", " if nums[left + (right-left+1) // 3] == target:\n", " return left + (right-left+1) // 3\n", "\n", " if nums[right - (right-left+1) // 3] == target:\n", " return right - (right-left+1) // 3\n", "\n", " if target > nums[left + (right-left+1) // 3]:\n", " # target must be on the left segment\n", " return ternarySearch(target,nums,left,left + (right-left+1) // 3 - 1)\n", "\n", " if target < nums[left + (right-left+1) // 3] and target > nums[right - (right-left+1) // 3]:\n", " # target must be on the middle segment\n", " return ternarySearch(target,nums,left + (right-left+1) // 3 + 1,right - (right-left+1) // 3-1)\n", "\n", " # target must be on the right segment\n", " return ternarySearch(target,nums,right - (right-left+1) // 3+1,right)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.1" } }, "nbformat": 4, "nbformat_minor": 2 }