Reputation: 17
public Song searchSongByName (String name) {
// ADD YOUR CODE HERE
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?
Upvotes: 1
Views: 456
Reputation: 285405
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
Arrays.stream(items)
// 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
.findFirst()
// return this item or null, if nothing found
.orElse(null);
Upvotes: 3
Reputation: 46
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];
Upvotes: 1
Reputation: 4833
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.
Upvotes: 3