|
| 1 | +%% Ternary Search |
| 2 | +% This function ternary searches target value in sorted (in increasing order) array. |
| 3 | +%%First, we compare the key with the element at mid1. If found equal, we return mid1. |
| 4 | +%If not, then we compare the key with the element at mid2. If found equal, we return mid2. |
| 5 | +%If not, then we check whether the key is less than the element at mid1. If yes, then recur to the first part. |
| 6 | +%If not, then we check whether the key is greater than the element at mid2. If yes, then recur to the third part. |
| 7 | +%If not, then we recur to the second (middle) part. |
| 8 | + |
| 9 | + |
| 10 | +% function for ternary search |
| 11 | +function [numComparisons, returnindex ] = ternarySearch( array, target, firstIndex , lastIndex) |
| 12 | +numComparisons = 0; |
| 13 | +lastIndex = length(array); |
| 14 | +firstIndex = 1; |
| 15 | + |
| 16 | +mid1 = firstIndex + (lastIndex - 1) / 3; %calculating mid1 |
| 17 | +mid2 = lastIndex - (lastIndex - 1)/ 3; %calculating mid1 |
| 18 | +xmid1 = 0; |
| 19 | +xmid2 = 0; |
| 20 | + |
| 21 | +if(array(mid1)== target) |
| 22 | + xmid1 = mid1; |
| 23 | + |
| 24 | +elseif(array(mid2) == target) |
| 25 | + xmid2 = mid2; |
| 26 | +elseif(target > array(mid1)) |
| 27 | + |
| 28 | + ternarySearch(array,mid2+1,lastIndex, target); |
| 29 | +elseif(target < array(mid1)) |
| 30 | + ternarySearch(array,firstIndex,mid1 - 1, target); |
| 31 | +else |
| 32 | + |
| 33 | + ternarySearch(array,mid1+1,mid2-1,target); |
| 34 | +end |
| 35 | +end |
0 commit comments