public class TernarySearch {
public int ternarySearch(int[] array, int target){
return ternarySearch(array,target,0,array.length-1);
}
private int ternarySearch(int[] array, int target, int left, int right){
if(left > right)
return -1;
int partitionSize = (right - left) / 3;
int mid1 = left + partitionSize;
int mid2 = right - partitionSize;
if(array[mid1] == target) {
return mid1;
}
if(array[mid2] == target) {
return mid2;
}
if(target < array[mid1]) {
return ternarySearch(array, target, left, mid1 - 1);
}
else if(target > array[mid2]) {
return ternarySearch(array, target, mid2 + 1, right);
}
return ternarySearch(array,target,mid1+1,mid2-1);
}
}
```*If we pass unsorted array it fails to find the index*
For example : Give the array ' int[] array = {2,8,7,9,15,19}; ' and target = 7 ;
it will return -1;
![image|690x448](upload://1mMBKfU5jWs5Z8H1AEJdcp93x7K.png)
Mosh mentions this: binary and ternary search both require a sorted array in order to be used. It is a prerequisite/ assumption we make before trying to use that algorithm. A better implementation might verify the assumption or sort the data itself in the constructor or something like that.