Binary Search - Algorithm
Binary search is a fastest search algorithm with o(log n) time complexity.this algorithm is based on divide and conquer.the searching technique required collection in sorted meaner. this is biggest disadvantage of binary search. suppose we need to search on array then first we need to sort array and the perform search operation on that array. the solution in this case is first sort array and the use Binary search on the array.
Algorithm :
Step 1: initialize low = 0, high = size of collection
step 2 : while low <= high then calculate the mid i.e mid = low + high/2
step 3 : if(searchValue == array[mid]){print Element found}
step 4 : if(searchValue > array[mid]){low = mid + 1} otherwise high = mid -1
step 5 : Exit
Programmatic Representation :
while(low <= high){
mid = low+high/2;
if(x== a[mid]){
Print : Element Found.
break;
}
if(x > a[mid]){
low = mid +1;
}else{
high = high -1;
}
}Java Program :
public class BinarySearchExample {
private void search(int[] array,int searchNumber) {
int low= 0;
int high = array.length;
int mid = 0;
while(low<= high) {
mid = (high + low )/2;
if(searchNumber==array[mid]) {
System.out.println("Value found at position "+mid);
}
if(searchNumber > array[mid]) {
low = mid + 1;
}else {
high = mid -1;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] array = {2,18,25,36,85,99};
BinarySearchExample be = new BinarySearchExample();
be.search(array, 99);
}
}
Comments
Post a Comment