I want to know how to do binary search on character array in java
There is a in-build function in java , but i don't want to use that , any help or pointers will be really appreciated.
I just started with below as i know binary search needs the array to be sorted
char[] whitelist = {'f','e','d','c','b','a'};
Arrays.sort(whitelist);
for (char ch : whitelist) {
开发者_运维知识库 System.out.println("The values after sorting\n"+ch);
}
As simple as Java does:
int binarySearch(char[] a, char key) {
int low = 0;
int high = a.length - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
char midVal = a[mid];
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
Of course, replace the array a
with your array, i.e. whitelist
.
Basically, look out for this - http://en.wikipedia.org/wiki/Binary_search_algorithm#Iterative
精彩评论