C中的三元搜索 [英] Ternary search in C

查看:48
本文介绍了C中的三元搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 C 中对整数进行三元搜索......我已经尝试过了......但它在特定情况下效果不佳.请帮我删除以下程序中的错误--

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 program--

我的尝试:

#include<stdio.h>
#include<conio.h>
void  tsearch(int *a,int i,int j,int k);
main() {
  int a[30],n,i,k;
        printf("\nEnter n:");
  scanf("%d",&n);
  printf("\nEnter nos in ascending order:");
  for(i=0;i<n;i++)
      scanf("%d",&a[i]);
  printf("Enter no to search:");
  scanf("%d",&k);
  tsearch(a,0,n-1,k);

  getch();
}

void tsearch(int *a,int i,int j,int k) {
  int m1,m2;
  m1=(i+j)/3;
  m2=2*(i+j)/3;
  if(k==a[m1])
   {
    printf("\nno found at %d",m1);
    return;
   }
  else  if(k==a[m2])
   {
    printf("\nno found at %d",m2);
    return;
   }
  if(k<a[m1])
    return(tsearch(a,i,m1-1,k));
  if(k>a[m2])
    return(tsearch(a,m2+1,j,k));
  else   
    return(tsearch(a,m1+1,m2-1,k));
}   

<小时>

如果要搜索的数字出现在(数组的)最后 2-3 个位置之一,则它(仅)终止.我在哪里犯了错误???


It (only) terminates if the number to be searched is present in one of last 2-3 locations (of array). Where i have committed the mistake???

推荐答案

中点计算错误.按照你的方式,m1 和 m2 不在 i 和 j 之间.

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

试试

 m1 = i + (j - i) * 1 / 3;
 m2 = i + (j - i) * 2 / 3;

这篇关于C中的三元搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆