www.gutterbucket.com | |||||||
Home | Software | Java | JS/HTML | General | Perl/CGI | Links | Sitemap |
If you pick a point in the middle of your ordered array (rounding down). Then by examine the points value you can determine if the item that you are looking for is after or before that point.
//This function returns the index of a match in array // or -1 if no match is found int binsearch(int target) { int lowend = 0; int highend = array.length-1; int midpoint; while (lowend <= highend) { midpoint = lowend + ((highend - lowend) / 2); if (array[midpoint] < target) { lowend = midpoint + 1; } else if (array[midpoint] > target) { highend = midpoint - 1; } else { return midpoint; } } return -1; }