|
| 1 | +/* Program to search data in given array using ternary search */ |
| 2 | + |
| 3 | +#include <stdio.h> |
| 4 | +#include <stdlib.h> |
| 5 | + |
| 6 | +// Function to search data in a given array |
| 7 | +int Ternary_search(int *arr,int l,int r,int to_search) |
| 8 | +{ |
| 9 | + //split current array into 3 part |
| 10 | + int Mid1=l+(r-l)/3,Mid2=r-(r-l)/3; |
| 11 | + // data not found condition |
| 12 | + if(l>r) |
| 13 | + return -1; |
| 14 | + // if data found in Mid1 index then return index number |
| 15 | + else if(arr[Mid1]==to_search) |
| 16 | + return Mid1; |
| 17 | + // if data found in Mid2 index then return the index number |
| 18 | + else if(arr[Mid2]==to_search) |
| 19 | + return Mid2; |
| 20 | + //else if data not found at index Mid1 and Mid2 then search in middle part of array |
| 21 | + else if(arr[Mid1]<to_search&&arr[Mid2]>to_search) |
| 22 | + { |
| 23 | + Mid1=Mid1+1; |
| 24 | + Mid2=Mid2-1; |
| 25 | + } |
| 26 | + // if data is less than Mid index data then search in before index number of current |
| 27 | + else if(arr[Mid1]>to_search) |
| 28 | + { |
| 29 | + Mid2=Mid1-1; |
| 30 | + Mid1=l; |
| 31 | + } |
| 32 | + // if data is less than Mid index data then search in after index number of current |
| 33 | + else if(arr[Mid2]<to_search) |
| 34 | + { |
| 35 | + Mid1=Mid2+1; |
| 36 | + Mid2=r; |
| 37 | + } |
| 38 | + // recursive calling the function |
| 39 | + return Ternary_search(arr,Mid1,Mid2,to_search); |
| 40 | +} |
| 41 | +// driver code |
| 42 | +int main() |
| 43 | +{ |
| 44 | + int n,*arr,i,to_search,res; |
| 45 | + printf("Enter size: "); |
| 46 | + // taking input |
| 47 | + scanf("%d",&n); |
| 48 | + // dynamically allocating array |
| 49 | + arr=(int*)malloc(sizeof(int)*n); |
| 50 | + for(i=0;i<n;i++) |
| 51 | + { |
| 52 | + scanf("%d",&arr[i]); |
| 53 | + } |
| 54 | + printf("Enter the number to search: "); |
| 55 | + // taking data to search |
| 56 | + scanf("%d",&to_search); |
| 57 | + // calling function to search index of given number and assign it in res |
| 58 | + res=Ternary_search(arr,0,n,to_search); |
| 59 | + // if res contain -1 that means data not found |
| 60 | + if(res==-1) |
| 61 | + printf("Data Not Found"); |
| 62 | + else |
| 63 | + printf("Data found at index no: %d",res); |
| 64 | + |
| 65 | +return 0; |
| 66 | + |
| 67 | +} |
| 68 | +/* |
| 69 | +Input: Enter size: 5 |
| 70 | + 1,2,3,4,5 |
| 71 | + Enter the number to search: 2 |
| 72 | +Output: Data found at index no: 1 |
| 73 | +
|
| 74 | +Time complexity: O(log3 n) |
| 75 | +Space complexity: O(1) |
| 76 | +
|
| 77 | +*/ |
0 commit comments