Answer:
Algorithm
The steps involved in this algorithm are:
(The list must be in sorted order)
• Step 1: Divide the search space (initially, the list) in three parts (with two mid-points: mid1 and mid2)
• Step 2: The target element is compared with the edge elements that is elements at location mid1, mid2 and the end of the search space. If element matches, go to step 3 else predict in which section the target element lies. The search space is reduced to 1/3rd. If the element is not in the list, go to step 4 or to step 1.
• Step 3: Element found. Return index and exit.
• Step 4: Element not found. Exit.
Complexity
• Worst case time complexity: O(log N)
• Average case time complexity: O(log N)
• Best case time complexity: O(1)
• Space complexity: O(1)
Algorithm
The steps involved in this algorithm are:
(The list must be in sorted order)
• Step 1: Divide the search space (initially, the list) in three parts (with two mid-points: mid1 and mid2)
• Step 2: The target element is compared with the edge elements that is elements at location mid1, mid2 and the end of the search space. If element matches, go to step 3 else predict in which section the target element lies. The search space is reduced to 1/3rd. If the element is not in the list, go to step 4 or to step 1.
• Step 3: Element found. Return index and exit.
• Step 4: Element not found. Exit.
Complexity
• Worst case time complexity: O(log N)
• Average case time complexity: O(log N)
• Best case time complexity: O(1)
• Space complexity: O(1)
#include <stdio.h>
int ternarySearch(int array[], int left, int right, int x)
{
if (right >= left) {
int intvl = (right - left) / 3;
int leftmid = left + intvl;
int rightmid = leftmid + intvl;
if (array[leftmid] == x)
return leftmid;
if (array[rightmid] == x)
return rightmid;
if (x < array[leftmid]) {
return ternarySearch(array, left, leftmid, x);
}
else if (x > array[leftmid] && x < array[rightmid]) {
return ternarySearch(array, leftmid, rightmid, x);
}
else {
return ternarySearch(array, rightmid, right, x);
}
}
return -1;
}
int main(void)
{
int array[] = {1, 2, 3, 5};
int size = sizeof(array)/ sizeof(array[0]);
int find = 3;
printf("Position of %d is %d\n", find, ternarySearch(array, 0, size-1, find));
return 0;
}
Step-by-step explanation: