This blog will soon be merged with

JavaByPatel

which explains each solution in detail, to visit new blog, click JavaByPatel

Tuesday, 16 June 2015

Check if a number exist in sorted array. (Implement Binary search in java using divide and conquer technique)


package search;

/*
	Find a number exist in array using Binary Search
	Binary Search can be applied to array only if the array is sorted.
	So if array is not sorted then first sort the array using any of the sorting algorithm which best suits the situation.
	Worst case performance		O(log n)
	Best case performance	 	O(1)
	Average case performance	O(log n)
	Worst case space complexity	O(1)
*/
public class BinarySearch {
	
	public static void main(String[] args) {
		int arr[] = new int[]{10, 20, 30, 40, 50, 60, 70, 80};
		System.out.println(search(arr, 80));
	}
	
	private static boolean search(int arr[], int data){
		if(arr==null || arr.length<0){
			return false;
		}
		
		int start=0;
		int end = arr.length-1;
		
		while(start<=end){
			int mid = start + (end-start)/2;
			
			if(arr[mid] == data){ //Exact Match
				return true; 
				
			}else if(arr[mid]>data){
				//Search on left
				end=mid-1;
			}else{
				//Search on right
				start=mid+1;
			}
		}
		return false;
	}
}



No comments:

Post a Comment