0 Replies - 403 Views - Last Post: 09 August 2006 - 12:31 PM

#1 SPlutard   User is offline

  • code.ninja
  • member icon

Reputation: 18
  • View blog
  • Posts: 615
  • Joined: 13-August 05

Binary Search Algorithm

Posted 09 August 2006 - 12:31 PM

Description: Using the divide and conquer idea, the Binary Search Algorithm can only function with SORTED arrays. The following code is just a method - not a full-fledged application. It needs three integer arguments (in this order): the integer array to be searched the length of the list the item to be searched forA very efficient search method for sorted arrays.
/* 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);
}


Is This A Good Question/Topic? 0
  • +

Page 1 of 1