Ternary search in C

前端 未结 4 904

I want to do a ternary search for integers in C ... I have tried it...but it\'s not working well for particular cases. Please help me to remove the bugs from the following progr

相关标签:
4条回答
  • 2021-01-24 03:28
    int a[30],n,i;
    scanf("%d",&n);
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    

    This is a typical buffer overflow issue. Allocate memory for a dynamically once you know what n is. uncleo solved your issue nicely. :)

    0 讨论(0)
  • 2021-01-24 03:36

    @uncleo makes a good point - and provides a decent solution.

    The bigger problem, though, is that if you search for a number that isn't in the array, there is nothing to stop the recursion - it continues until it crashes.

    Also, the design of tsearch() is suspect; the code shown says it is a void function, yet you use return(tsearch(...)); several times (as well as a couple of plain return; statements). Surely, the function should return an int and the two plain return; statements should return m1 or m2? You also need to deal with the case where the range is degenerate (i >= j) which means the value is not present - maybe you can return -1 or something similar for that case.

    0 讨论(0)
  • 2021-01-24 03:38

    The midpoint calculations are wrong. The way you have it, m1 and m2 are not between i and j.

    try

     m1 = i + (j - i) * 1 / 3;
     m2 = i + (j - i) * 2 / 3;
    
    0 讨论(0)
  • 2021-01-24 03:41
    #include<stdio.h>
    
    int  tsearch(int *a,int i,int j,int k);
    
    int main() {
          int a[10]={1,2,3,4,5,6,7,8,9,10};
          int search;
          int k;
          printf("enter no to be searched :");
          scanf("%d",&k);
          search=tsearch(a,0,9,k);
          printf("\n%d",search);
          return 0;
    }
    
    int tsearch(int *data, int left, int right, int value){
        int i;
        int first,second;
        if(left>right)
           return -1;
    
        i= (right - left)/3;
        if(i==0) i++;
    
        first = i  + left -1;
        second = i*2 + left - 1;
    
        if(data[first]==value)
           return first;
        else
        if(data[first]>value)
             return tsearch(data, left, first-1, value);
        else
         {
            if(data[second]==value)
              return second;
            else
            if(data[second]>value)
               return tsearch(data, first+1,second-1, value);
            else
               return tsearch(data, second+1,right, value);
         }
    }
    
    0 讨论(0)
提交回复
热议问题