Tuesday 22 January 2013

Ternary search

Easy Method :


#include  
#include 
  int main()
  {
    int a[20], n, i, mid1, mid2, max, min, s;
    printf("enter the order\n");
    scanf("%d", & n);
    printf("enter the number elements");
    for(i = 0; i < n; i++)
    {
      scanf("%d", & a[i]);
    }
    printf("enter the serching element\n");
    scanf("%d", & s);
    min = 0;
    max = n - 1;
    mid1 = (2 * min + max) / 3;
    mid2 = (min + 2 * max) / 3;
    while(mid1 != mid2)
    {
      mid1 = (2 * min + max) / 3;
      mid2 = (min + 2 * max) / 3;
      if(s <= a[mid1])
        max = mid1;
      else
      if(s > a[mid1] && s <= a[mid2])
      {
        min = mid1;
        max = mid2;
      }
      else
        min = mid2;
    }
    if(s == a[max])
    {
      printf("number is found\n\n position is=%d", max + 1);
    }
    else
    {
      printf("number is not found");
    }
    getch();
  }
Run Time Order
T(n) = T(2 / 3 * n) + c
Θ(log n)

No comments:
Write comments

Featured post

List of Universities in Karnataka offering M.Sc Computer Science

The post-graduate programme in Computer Science (M.Sc Computer Science) contains two academic years duration and having a four semesters....

Popular Posts

Copyright @ 2011-2022