Open In App
Related Articles

Algorithms | Searching | Question 6

Improve Article
Save Article
Like Article

Which of the following is the correct recurrence for the worst case of Ternary Search?


   T(n) = T(n/3) + 4, T(1) = 1


  T(n) = T(n/2) + 2,  T(1) = 1


  T(n) = T(n + 2) + 2,  T(1) = 1


  T(n) = T(n – 2) + 2,  T(1) = 1

Answer: (A)


Following is a typical implementation of Binary Search. 

// A recursive ternary search function. It returns location of x in
// given array arr[l..r] is present, otherwise -1
int ternarySearch(int arr[], int l, int r, int x)
if (r >= l)
		int mid1 = l + (r - l)/3;
		int mid2 = mid1 + (r - l)/3;

		// If x is present at the mid1
		if (arr[mid1] == x) return mid1;

		// If x is present at the mid2
		if (arr[mid2] == x) return mid2;

		// If x is present in left one-third
		if (arr[mid1] > x) return ternarySearch(arr, l, mid1-1, x);

		// If x is present in right one-third
		if (arr[mid2] < x) return ternarySearch(arr, mid2+1, r, x);

		// If x is present in middle one-third
		return ternarySearch(arr, mid1+1, mid2-1, x);
// We reach here when element is not present in array
return -1;

In ternary search, we divide the given array into three parts and determine which has the key (searched element). We can divide the array into three parts by taking mid1 and mid2 which can be calculated as shown below. Initially, l and r will be equal to 0 and n-1 respectively, where n is the length of the array. So the recurrence relation is    T(n) = T(n/3) + 4, T(1) = 1

Hence Option (A) is the correct answer.

Quiz of this Question
Please comment below if you find anything wrong in the above post

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 28 Jun, 2021
Like Article
Save Article
Similar Reads