Binary search algorithem method/function for j2me platform.
Use is with sorted String array!!!
Enjoy... this works great with my example on J2ME | String array sort. link here.
public static int binarySearch(String[] p_arraySorted, String p_key)
{
return binarySearch(p_arraySorted, 0, p_arraySorted.length, p_key);
}
public static int binarySearch(String[] p_arraySorted, int p_first, int p_upto, String p_key)
{
int compare, mid;
while (p_first < p_upto)
{
// Compute mid point.
mid = (p_first + p_upto) / 2;
compare = p_key.compareTo(p_arraySorted[mid]);
if (compare < 0) // p_key < p_arraySorted[mid]
{
// repeat search in bottom half
p_upto = mid;
}
else if (compare > 0) // p_key > p_arraySorted[mid]
{
// Repeat search in top half
p_first = mid + 1;
}
else
{
// Found it. return position
return mid;
}
}
// Failed to find key
return -1;
}
Sort it and search it wisely...
By using Object[] instead of String[] you can create GENERIC BINARY SEARCH ALGORITHM for J2ME...
ReplyDeletegood job.