Quantcast
Channel: Computer Programming Tutor » Java
Viewing all articles
Browse latest Browse all 2

Binary Search

$
0
0

Binary Search is a faster alternative to sequential search.  Binary search can be used to find a value in an array, however the array must already be sorted.  If the array is not sorted then binary search may not find the value.  Binary search works by first looking at the middle of the array.  If the value is found the search stops, otherwise the if the search value is less than the middle value it looks in the first half of the array and it is larger then it looks in the second half.  Much in a way that one might look up a word in a dictionary.

Binary Search

As shown above in the array we first look at the middle value which is 6 and since 5 is less than 6 we look at the left portion of the array.  Then we look at the middle of that portion.  It has a even number of elements so we just pick an element either to left or the right of the real middle.  Which one the algorithm chooses depend on how you write it, but has no outcome on if the value is found or not.  In this case we choose the element to the left.  Three is less than 5 so we look to the portion to the right.  Then we look at 4 which is still too small so we look to the right and find 5.

public class Search {
	public static void main(String[] args){
		int[] a = {1, 3, 4, 5, 6, 7, 8, 9, 0};
		int position = Search.binarySearch(a, 5);
		System.out.println(position);
	}
	
	public static int binarySearch(int[] array, int searchValue){
		int start = 0;
		int end = array.length;
		int middle = 0;
		
		while(start < end){
			middle = (start + end) / 2;
			if(array[middle] == searchValue){
				return middle;
			}
			if(array[middle] > searchValue){
				end = middle;
			}else{
				start = middle;
			}
		}
				
		return -1;
	}
}

 


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images