|
| 1 | +// C program to illustrate |
| 2 | +// recursive approach to ternary search |
| 3 | + |
| 4 | +#include <stdio.h> |
| 5 | + |
| 6 | +// Function to perform Ternary Search |
| 7 | +int ternarySearch(int l, int r, int key, int ar[]) |
| 8 | +{ |
| 9 | + if (r >= l) { |
| 10 | + |
| 11 | + // Find the mid1 and mid2 |
| 12 | + int mid1 = l + (r - l) / 3; |
| 13 | + int mid2 = r - (r - l) / 3; |
| 14 | + |
| 15 | + // Check if key is present at any mid |
| 16 | + if (ar[mid1] == key) { |
| 17 | + return mid1; |
| 18 | + } |
| 19 | + if (ar[mid2] == key) { |
| 20 | + return mid2; |
| 21 | + } |
| 22 | + |
| 23 | + // Since key is not present at mid, |
| 24 | + // check in which region it is present |
| 25 | + // then repeat the Search operation |
| 26 | + // in that region |
| 27 | + |
| 28 | + if (key < ar[mid1]) { |
| 29 | + |
| 30 | + // The key lies in between l and mid1 |
| 31 | + return ternarySearch(l, mid1 - 1, key, ar); |
| 32 | + } |
| 33 | + else if (key > ar[mid2]) { |
| 34 | + |
| 35 | + // The key lies in between mid2 and r |
| 36 | + return ternarySearch(mid2 + 1, r, key, ar); |
| 37 | + } |
| 38 | + else { |
| 39 | + |
| 40 | + // The key lies in between mid1 and mid2 |
| 41 | + return ternarySearch(mid1 + 1, mid2 - 1, key, ar); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + // Key not found |
| 46 | + return -1; |
| 47 | +} |
| 48 | + |
| 49 | +// Driver code |
| 50 | +int main() |
| 51 | +{ |
| 52 | + int l, r, p, key; |
| 53 | + |
| 54 | + // Get the array |
| 55 | + // Sort the array if not sorted |
| 56 | + int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; |
| 57 | + |
| 58 | + // Starting index |
| 59 | + l = 0; |
| 60 | + |
| 61 | + // length of array |
| 62 | + r = 9; |
| 63 | + |
| 64 | + // Checking for 5 |
| 65 | + |
| 66 | + // Key to be searched in the array |
| 67 | + key = 5; |
| 68 | + |
| 69 | + // Search the key using ternarySearch |
| 70 | + p = ternarySearch(l, r, key, ar); |
| 71 | + |
| 72 | + // Print the result |
| 73 | + printf("Index of %d is %d\n", key, p); |
| 74 | + |
| 75 | + // Checking for 50 |
| 76 | + |
| 77 | + // Key to be searched in the array |
| 78 | + key = 50; |
| 79 | + |
| 80 | + // Search the key using ternarySearch |
| 81 | + p = ternarySearch(l, r, key, ar); |
| 82 | + |
| 83 | + // Print the result |
| 84 | + printf("Index of %d is %d", key, p); |
| 85 | +} |
0 commit comments