What do I return for binary search of objects?

binary search java
binary search arraylist of objects java
binary search python
binary search program in c++
binary search example step by step
recursive binary search
binary search without recursion
binary search time complexity
public Song searchSongByName (String name) {
  int low = 0;
  int high = items.length - 1;
  String foundName = "";
  while ( low <= high ) {
    int mid = (high + low) / 2;
    if ( items[mid].getName().compareTo(name) == 0) {
      foundName+= name;;
    } else {

      if ( items[mid].getName().compareTo(name) == -1 ) {
        low = mid;
      } else {
        high = mid;


This is for a project I'm working on, basically, "items" is an object array of songs and I need to search the array looking for the song given in the parameter. My first idea was to return just the string i made "foundName" but that didn't work out. Then I thought of return -1 (if not found) and 0 (if found) but the return type is Song. So what can I return to let the user know that their song was found?

I think that items is something like that

Song[] items = ...

So you should return this if found

// instead of line // foundName+= name;;
return items[mid];

And return null after the while loop, if not found.

But if you can change the return type of your method you should rather return an Optional:

// instead of line // foundName+= name;;
return Optional.of(items[mid]);

In this case return Optional.empty(), if not found.

Implementing binary search of an array (article), What should happen if the number you are looking for is not in the array? Let's start by figuring out what index the binarySearch function should return in this case. Return Type: If the item is found, then this method returns the zero-based index of the element to be searched for and if not found, then a negative number that is the bitwise complement of the index of the next element will be return and the complement is larger than that item.

One solution is to use Java 8 streams, to wit:

// written to return null if song name not found
public static Song searchSong(String name) {        
    return Arrays.stream(items)
            .filter(e -> e.getName().equalsIgnoreCase(name))

improved as per Makoto's comment

code breakdown:

// convert items array into a Stream using java.util.Arrays

    // filter the Stream to get only Songs whose name match the name String (ignoring case)
    .filter(e -> e.getName().equalsIgnoreCase(name))

    // find the first item in the filtered Stream

    // return this item or null, if nothing found

Collections.binarySearch() in Java with Examples, The method throws ClassCastException if elements of list are not comparable return u1.getId().compareTo(u2.getId());. } }; // Searching a domain with key value 10. Collections.binarysearch() works for objects Collections like ArrayList and  Returns Int32. The index of the specified value in the specified array, if value is found; otherwise, a negative number. If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value.

Binary search returns the index where the element is found in an array of objects. It does not return the element itself.

Hence, the return type of binary search method should be int.

To get the object itself later, as an example you can do:

int index = binarySearch("Never Gonna Give You Up");
if (index > -1)
  Song rickAstleySong = items[index];

Arrays.binarySearch() in Java with examples, public static int binarySearch(data_type arr, data_type key ) any of the primitive data types: byte, char, double, int, float, short, long and Object as well. Note that this guarantees that the return value will be >= 0 if and only if the key is found. This method returns index of the search key, if it is contained in the array, else it returns (- (insertion point) - 1). The insertion point is the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key.

Java's Binary Search API in Five Minutes, The methods return an int representing the index of the found search key If you are using the binary search method for an Object array, the  Value to search for in the range. For (1), T shall be a type supporting being compared with elements of the range [first,last) as either operand of operator<. comp Binary function that accepts two arguments of the type pointed by ForwardIterator (and of type T), and returns a value convertible to bool. The value returned indicates whether the first argument is considered to go before the second.

Java.util.Arrays.binarySearch() Method, If it is not sorted, the results are undefined. Declaration. Following is the declaration for java.util.Arrays.binarySearch() method public static int binarySearch(Object  A simple approach is to do linear search. The time complexity of above algorithm is O (n). Another approach to perform the same task is using Binary Search. Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half.

Binary Search, Linear search can be used to look through the entries one-by-one starting with the first entry If the object is found, return the index of the object in the array. Good day! I have a List of ValueObj: class ValueObj { int ID; float value; } How to get binary search objects by id? (List tempValues) I make ValueComparer class,but dont know am i righ

  • You stated that items is an array of Song, and that the method needs to return a Song object, so why not simply return items[mid] object if its name matches the name String? This would make the most sense to me.
  • Also, why not simply iterate through the array using a for loop? or using a Stream?
  • what can I return if their song is never found?
  • @GGar That would be upto the contract of the method- return null is one option, raising an exception is another, returning a dummy object a third.
  • Either return null or throw an exception such as an IllegalArgumentException
  • You could shorten this to return optionalSong.orElse(null) to make this more concise. Returning the optional would be the most ideal but this is an okay compromise.