# Binary Search Algorithm

Page 1 of 1

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

### #1 SPlutard

• code.ninja

Reputation: 18
• 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;
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

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }