I am doing an application where I want to find a specific char in an array of chars. In other words, I have the following char array:
char[] charArray= new char[] {'\uE001', '\uE002', '\uE003', '\uE004', '\uE005', '\uE006', '\uE007', '\uE008', '\uE009'};
At some point, I want to check if the character '\uE002' exists in the charArray. My method was to make a loop on every character in the charArray and find if it exists.
for (int z = 0 ; z < charArray; z ++) {
if (charArray[z] == myChar) {
//Do the work
}
}
Is there any other solution than making a char array and finding the character by looping every single char?
One option is to pre-sort
charArrayand useArrays.binarySearch(charArray, myChar). A non-negative return value will indicate thatmyCharis present incharArray.edit An alternative that avoids using the
Arraysmodule is to put the characters into a string (at initialization time) and then use String.indexOf():This is not hugely different to what you’re doing already, except that it requires less code.
If
nis the size ofcharArray, the first solution isO(log n)whereas the second one isO(n).