Sunday 10 July 2016

Binary Search Program in java using divide and conquer method

Binary Search Program in java using devide and conquer method.

Every thing i did static we can do in dynamic way by using scanner.

package com.prabhu;

public class BinarySearch {
public static void main(String[] args) {
int total=7;
int array[] = {2,4,7,1,3,9,5};
int item = 3;
int first=0;
int last=total-1;
int middle = (first+last)/2;

while(first<=last){
if(array[middle]<item){
first=middle+1;
}else if(array[middle] ==item){
System.out.println("item is in this position: "+ (middle+1));
break;
}else{
last=middle-1;

}
middle = (first+last)/2;
}
if(first>last)
System.out.println("item is not found");
}
}

Output:
item is in this position: 5

No comments:

Post a Comment