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