Core JavaJava

Binary Search in Java

This post explains :

– Java code for binary search in list

– searching lists in java

– java code for recursive binary search

– java code for iterative binary search

 

Searching List in Java

If a list is not sorted, searching can only be done by element by element by comparison. So, its better to sort an unsorted list before running search.

Binary search focuses on half of the list only and then narrows down the search by again taking half of the elements and so on. Binary search can search the list effectively this way since the list is a sorted list. This approach won’t work unless the list is sorted before the binary search.

 

You can do a binary search on sorted list directly using following library function:

Collections.binarySearch(List, Object)

An unsorted list can be sorted using Collections.sort() method.

 

However, if you need algorithms for binary search using recursive or iterative approach, following programs can be helpful.

 

Recursive Binary Search

The below program is an example of binary search on a sorted list using recursion.

 

Iterative Binary Search

The below program is an example of binary search on a sorted list using iterative approach. It returns index of the element in the list.

 

 

© 2015, www.techkatak.com. All rights reserved.