Using Comparable in Binary Search

• November 11th, 2011, 02:41 AM
Shaybay92
Using Comparable in Binary Search
So I have written some code which tells whether a certain Integer is within a list of integers. I tried to do this with a comparable type instead of 'integer' type, but I realised that this wouldn't work as we could have say a String and Integer in the same list. I want to be able to have comparables of all the same type, but not limited to just Integers... Does anyone know how I could do this? I'm not very confident with using interfaces as input parameters. This is my code:

Code :

```package Recursion;   import java.util.ArrayList; import java.util.List; import java.util.Scanner;   public class BinarySearch { // Takes in a sorted list (ascending order) of comparable objects // and finds whether a certain object is in that list using binary // search method.   public static void main(String[] args){ ArrayList<Integer> l = new ArrayList<Integer>(); l.add(3); l.add(10); l.add(30); l.add(502); System.out.println(l); Scanner s = new Scanner(System.in); while(s.hasNextInt()){ int n = s.nextInt(); System.out.print(BinarySearch.search(l, n)); } }   //Check whether something is in the list public static boolean search(List<Integer> al, Integer c){ //Current one we are looking at Integer pivot = al.get(al.size()/2);   if (c.equals(pivot)){ return true; } else if (c.compareTo(pivot) == -1){ if (al.size()/2 == 0){ //if our pivot is the first value in the sorted list return false; // no more to see } else { return search(al.subList(0,al.size()/2),c); } } else { if(al.size()/2 == 0){ return false; } else { return search(al.subList(al.size()/2,al.size()),c); } }   }   }```
• November 11th, 2011, 09:02 AM
kenster421
Re: Using Comparable in Binary Search
The comparable interface will assist you in comparing objects.

Comparable (Java 2 Platform SE v1.4.2)

You will need to implement the methods in your class BinarySearch when you add the interface. You will create the rules in method compareTo() for when a certain BinarySearch is different from another. Be sure to read the rules in the link.
• November 12th, 2011, 01:24 AM
Shaybay92
Re: Using Comparable in Binary Search
I understand that I have to implement the interface to use a data type as a 'comparable'.. however this is not my issue. The issue is that I want my list to contain any type which implements comparable, but I want it to be so only one type can be in the list at a time. For example, I could use this code to make and search a list of Integers as they are comparable, or a list of Strings, but I dont want to be able to have integers and strings in the same list.

By making the input list type List<Comparable> this doesnt force the elements to be of one comparable type, but various types.
• November 12th, 2011, 02:23 AM
helloworld922
Re: Using Comparable in Binary Search
I would suggest using a Comparator instead.