Here is your code below: –
import java.util.Scanner; public class TernarySearch
public static int ternarySearch(int[] A, int value) return terSearch(A, 0, A.length – 1, value);
}
public static int terSearch(int9 A, int I, int r, int x) if (I > r) return -1;
int midl = I (r – I) / 3;
int mid2 = midl (r – I) / 3;
if (A[midl] == x) return midi;
else if (A[mid2] == x) return mid2;
else if (x
else if (x > A[mid2]) return terSearch(A, mid2 1, r, x);
else return terSearch(A, midi, mid2, x);
}
public static void main(String[] args) Scanner scan = new Scanner(System.in); System.out.println(“Ternary Search Test\ n”); int n,
System.out.println(“Enter number of integer elements”); n = scan.nextInt();
int aril] = new int[n];
System.out.printIn(“\nEnter ” n ” sorted integer elements”); for (i = 0; i
int result = ternarySearch(arr, key);
if (result == -1) System.out.printIn(” n” key – element not found”); else System.out.printIn(” \n” key – element found at position ” result);
Sample Run: – 1. Ternary Search Test Enter number of integer elements
6
Enter 6 sorted integer elements 1 2 3 4 5 6
Enter element to search for : 7
7 element not found 2. Ternary Search Test Enter number of integer elements
6
Enter 6 sorted integer elements 1 2 3 4 5 6
Enter element to search for : 4
4 element found at position 3
#Sales Offer!| Get upto 25% Off: