#include<stdio.h> // this code is for the recursive implementation of ternary search int ternarysearch(int l, int r, int key,int ar[]) { if(r >= 1){ int mid1 = l + (r-1)/3; int mid2 = r - (r-1)/3; if (ar[mid1] == key){ return mid1; } if (ar[mid2] == key){ return mid2; } if(key < ar[mid1]){ return ternarysearch(1, mid1-1,key,ar); } else if(key > ar[mid2]){ return ternarysearch(mid2+1, mid2-1,key,ar); } } return -1; } int main() { int l,r,p,key; //sort the array if the array is not sorted int ar[] = {1,2,3,4,5,6,7,8,9,10}; l=0; r=9; key= 5; p= ternarysearch(l, r,key,ar); printf("index of %d is%d\n", key,p); key = 50; p= ternarysearch(l, r, key, ar); printf("index of %d is %d",key , p); }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter