Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Ternary Search

I am trying to perfrom a ternary search on a array of strings. I have got most of code down and I think I am going on the right track but can't seem to get any results other then -1. Below is the code that I have genearated thus far. I know the problem is in the search algorithm. I do not want to use any built is as I am learning.

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;
} 
like image 297
M Lill Avatar asked May 31 '26 11:05

M Lill


2 Answers

You never get into the loop.

int start=0, end=x.length;
while (start > end)
like image 161
Thomas Avatar answered Jun 03 '26 01:06

Thomas


You're while statement is wrong, it should contain start < end. I recomend learning the debug settings that are on most IDEs because if you're going to stick around it makes it so much easier to view the states of vars.

like image 35
Feek Avatar answered Jun 02 '26 23:06

Feek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!