I did some research and wasn't able to find anything but if this is a duplicate please let me know.
I have this code for binary search of integers
package thepac;
public class CustomBS{
public static void main(String[] args){
int[] listOfNumbers = new int[]{2,45,65,76,89,100,342,455};
int numberToSearch = 100;
int lowestIndex = 0;
int highestIndex = listOfNumbers.length-1;
int middleIndex;
while(lowestIndex<=highestIndex){
middleIndex = (lowestIndex+highestIndex)/2;
if(numberToSearch > listOfNumbers[middleIndex]){
lowestIndex = middleIndex+1;
}else if(numberToSearch < listOfNumbers[middleIndex]){
highestIndex = middleIndex-1;
}else{
break;
}
}//end of while
if(lowestIndex > highestIndex){
System.out.println("not found");
}else{
System.out.println("found");
}
}
}
This works just find and I understand the concept. Is it possible to implement a version of this that searches for Strings as in an array of Strings?
I can't think of how to implement this since the current algorithm checks if the number being searched is higher or lower than the middle index, but if it's a String, how do I check if it's higher or lower than another string?
I know I can use the String.compareTo() method to check if a string is larger or shorter than another one but I'm not sure if this would be the correct way of implementing this.
String.compareTo()method if you want to write your own implementation.path/to/JDK/src.zip. You can find some examples here, here, here,...