/* Snippet: Binary Search
* Author: SPlutard
*
*Description: An efficient method for searching SORTED arrays. Returns the number if found, otherwise returns -1.
*/
public static int binarySearch(int[] list, int listLength, int searchItem) {
int first=0;
int last = listLength - 1;
int mid;
boolean found = false;
//Loop until found or end of list.
while(first <= last &&!found) {
//Find the middle.
mid = (first + last) /2;
//Compare the middle item to the search item.
if(list[mid] == searchItem) found = true;
else { //Not found, readjust search parameters, halving the size & start over.
if(list[mid] > searchItem) last = mid -1;
else first = mid + 1;
}
}
if(found) return mid;
else return(-1);
}
* Author: SPlutard
*
*Description: An efficient method for searching SORTED arrays. Returns the number if found, otherwise returns -1.
*/
public static int binarySearch(int[] list, int listLength, int searchItem) {
int first=0;
int last = listLength - 1;
int mid;
boolean found = false;
//Loop until found or end of list.
while(first <= last &&!found) {
//Find the middle.
mid = (first + last) /2;
//Compare the middle item to the search item.
if(list[mid] == searchItem) found = true;
else { //Not found, readjust search parameters, halving the size & start over.
if(list[mid] > searchItem) last = mid -1;
else first = mid + 1;
}
}
if(found) return mid;
else return(-1);
}
0 komentar:
Posting Komentar