1

Currently stuck on a problem with binary search that is asking me to pass one parameter with is an object. But is it possible to do this?? Normally I would use two parameters for a problem like this. Normally with binary search I use-->

int binarySearch(int[] list, int searchItem) 
{ 
int mid=0; 
int start=0; 
int end=list.length-1; 
boolean found=false; 

//Loop until found or end of list. 
while (start <= end && !found) 
{ 
mid = (start + end) / 2; 
if (list[mid] == searchItem)
  found = true;
else 
  if (list[mid] > searchItem) 
    end = mid - 1;
  else 
    start = mid + 1;
}
if(found) 
return mid;
else 
 return(-1);
}

But is it possible to just pass in one parameter like this?? I need to search an array list.

  public int binarySearch(Moon searchItem){
  int mid = 0;
  int start = 0;
  int end = moons.size() -1;
  boolean found = false;

  while(start <= end && !found){
      mid = (start + end) / 2;
      if(moons.get(mid).equals(searchItem)){
          found = true;
      }
      else{
          if(???)) {
          }
          else
            etc etc     
      }    
  }
  return 0;
}
James A
  • 111
  • 4
  • If you can replace `list[mid]` with `moons.get(mid)` then you can do it twice! replace your `???` with `moons.get(mid)` as well! (And then as Azodious mentioned you need to compare objects, but you haven't really posted a lot of context - it looks like you got a lot of code from someone so perhaps your Moon already has a `compareTo` method) – Erwin Bolwidt Dec 21 '16 at 07:21

1 Answers1

0

First you should go through this question: How to compare objects by multiple fields

Then, implement Comparable to Moon class. If you can't change Moon class, then you've to create Comparator.

You'll need to override compareTo method in Moon class which can be used in place of ??? in your question.

Community
  • 1
  • 1
Azodious
  • 13,752
  • 1
  • 36
  • 71