编程语言
首页 > 编程语言> > Java三元搜索

Java三元搜索

作者:互联网

我试图在一系列字符串上进行三元搜索.我已经完成了大部分代码,我认为我正在走上正确的轨道,但似乎除了-1之外似乎没有得到任何结果.下面是我迄今为止已经创建的代码.我知道问题出在搜索算法中.我不想使用任何内置的,因为我正在学习.

public static void main(String[] args) {
    //declare a string array with initial size
    String[] songs =  {"Ace", "Space", "Diamond"};
    System.out.println("\nTest binary (String):");
    System.out.println(search(songs,"Ace"));

}  

public static int search(String[] x, String target) {     

   int start=0, end=x.length;

   while (start > end) {
      int midpoint1 = start+(end - start)/3;
      int midpoint2 = start +2*(end-start)/3;
      if ( target.compareTo(x[midpoint1]) == 0 ) 
          return midpoint1;
      else if ( target.compareTo(x[midpoint2]) == 0 ) 
          return midpoint2;   
      else if ( target.compareTo(x[midpoint1]) < 0 ) 
          return end = midpoint1-1;
      else if ( target.compareTo(x[midpoint2]) > 0 ) 
          return start = midpoint2+1;
  }

   return -1;
} 

解决方法:

你永远不会进入循环.

int start=0, end=x.length;
while (start > end)

标签:ternary,java,search
来源: https://codeday.me/bug/20190829/1764441.html