# Ternary Search Algorithm Implementation (BUG FOUND)

**URL:** <https://forum.codewithmosh.com/t/ternary-search-algorithm-implementation-bug-found/8398>\
**Category:** Data Structures\
**Created:** [November 9, 2021, 1:31pm UTC](https://forum.codewithmosh.com/t/ternary-search-algorithm-implementation-bug-found/8398 "2021-11-09T13:31:38Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jack007](https://avatars.discourse-cdn.com/v4/letter/j/7c8e57/32.png) [@jack007](https://forum.codewithmosh.com/u/jack007)\
**Post date:** [November 9, 2021, 1:31pm UTC](https://forum.codewithmosh.com/t/ternary-search-algorithm-implementation-bug-found/8398/1 "2021-11-09T13:31:38Z")

</div>

````auto
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)
````

---

<div class="post-metadata">

**Author:** ![jack007](https://avatars.discourse-cdn.com/v4/letter/j/7c8e57/32.png) [@jack007](https://forum.codewithmosh.com/u/jack007)\
**Post date:** [November 9, 2021, 1:32pm UTC](https://forum.codewithmosh.com/t/ternary-search-algorithm-implementation-bug-found/8398/2 "2021-11-09T13:32:32Z")

</div>

![image](https://us1.discourse-cdn.com/flex020/uploads/codewithmosh/original/2X/0/0995811c7fe691b9a4fe428fb9a1eea19f1b453c.png)

---

<div class="post-metadata">

**Author:** ![jmrunkle](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/jmrunkle/32/3765_2.png) [@jmrunkle](https://forum.codewithmosh.com/u/jmrunkle)\
**Post date:** [August 4, 2022, 2:09pm UTC](https://forum.codewithmosh.com/t/ternary-search-algorithm-implementation-bug-found/8398/3 "2022-08-04T14:09:13Z")

</div>

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.
