0

I was learning how to implement binary search on an array of objects of a user-defined class. I came across this question.

I perfectly understood the program given in the top-voted answer. When doing binary search, say line 27 in the program,

Collections.binarySearch(l, new User(20, null), c);

From what I understood, I guess that it is searching for such an User object, in the ArrayList l sorted using Comparator c, which contains 20. null is passed in place of as String name argument.

To further improve on this program, what changes could be made to search for an User object which contains "A" in its name variable? And search for it based only on name, assume that we have no knowledge of its id.

Edit: I have given a link to a similar question, and I am not asking for the same logic. I am asking for an improvement on that question.

And to clear some confusion, in the linked question

Collections.binarySearch(l, new User(20, null), c);

is used so that an object with id 20 is searched with no idea of name (because null is passed). I am trying to understand vice-versa. Searching for an object using its name and no idea of id, something like doing

Collections.binarySearch(l, new User(null, "A"), c);
Community
  • 1
  • 1
Jeet Parekh
  • 740
  • 2
  • 8
  • 25
  • Instead of `return u1.getId().compareTo(u2.getId());` in the comparator, it would be `return u1.getName().compareTo(u2.getName());` – Robert Harvey May 19 '15 at 19:15
  • @RobertHarvey that would sort the ArrayList according to its name, but would it search for the object based only on its name? – Jeet Parekh May 19 '15 at 19:16
  • Do like to search for an entry for which the name *contains* the letter "A" (then iterate over all and check name.contains("A")) or do you like to search for an entry for which the name *equals* the string "A" (then the first comment works). – Christian Fries May 19 '15 at 19:24

1 Answers1

0

You can only apply the binary search when the input array is sorted with respect to property you are searching for.

So in your case the list of users have to be ordered by their user name property. You can sort the list with the same comparator to achieve this.

In Java:

Collections.sort(l, c);
Crine
  • 805
  • 7
  • 24