What is binary search: It is an efficient algorithm which is used to find the position of a target value within a sorted array or list. This works by repeatedly dividing the search range in half, hence it is also known as two parts.
The data should be stored in ascending or descending order.
Linear search: This is the simplest searching algorithm that checks each element in the list one by one until the target element is found.
For large data, linear search is not suitable.
Ex: To find birthday date of a person:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
- minimum value = 1, maximum value = 31 mid = (1+31)/2 = 16
- Then, consider minimum value as 17 (min = max+1) mid = (17+31)/2 = 24
- Now we should consider minimum value as 17, maximum value = mid - 1, then max = 23.
Ex 1: To find the key value
class Book{
public static void main(String[] args){
int [] array = {10,12,28,41,66,72,89};
int Key = 72;
int min = 0;
int max = array.length - 1;
while (min<=max){
int mid = (min+max)/2;
if (Key == array[mid]){
System.out.println("Key found at" + mid);
break;
}
else if (Key < array[mid]){
max = mid - 1;
}
else {
min = mid + 1;
}
}
}
}
Output:
Key found at 5
Why to use break statement: If the first condition itself satisfied, the a break statement can be used.
Ex 2: To check whether a given number is double digit
class Book{
public static void main(String[] args) {
int num = 1;
if (num >= 10 && num <= 99) {
System.out.println(" double-digit number.");
} else {
System.out.println("not a double-digit number.");
}
}
}
Output: not a double-digit number
Top comments (0)