What is binary search.
It is a searching technique that is used when the input sequence is already in sorted order.
It is used to find a particular element from a given source. It is a basic technique that is used in various applications because it has searching complexity of (Log [base2] N).
Steps in binary searching
1. In this the input number to be searched is compared with the middle element of the array
2. If it is smaller than the middle element the then the left part is searched otherwise the right part is searched
3. Every time the element is not found the remaining array is divided into two parts [left one] and [right one]
4. It performs total log2n comparisons to find the input element
5. For example if there are total 1024 elements the n it performs only 10 comparisons to identify the element
Program
import java.io.IOException;
import java.io.InputStreamReader;
public class BinarySearch {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of elements");
int num = Integer.parseInt(br.readLine());
int a[] = new int[num];
System.out.println("Please enter");
for (int i = 0; i < num; i++) {
a[i] = Integer.parseInt(br.readLine());
}
System.out.println("Enter the element to search");
int find = Integer.parseInt(br.readLine());
int index = search(a, find);
if (index != -1) {
System.out.println("Element found : " + index);
} else {
System.out.println("Element not found");
}
}
public static int search(int ar[], int find) {
int start = 0;
int end = ar.length - 1;
int mid;
while (start <= end) {
mid = (start + end) / 2;
if (ar[mid] == find) {
return mid;
} else if (ar[mid] < find) {
start = mid + 1;
} else if (ar[mid] > find) {
end = mid - 1;
}
}
return -1;
}
}
No comments:
Post a Comment