5, 7, 9, 11, 15, 20, 30, 45, 89, 97
5, 7, 9, 11, 15, 20, 30, 45, 89, 97
15 found at position 5
class BSearch {
int A[] = {5, 7, 9, 11, 15, 20, 30, 45, 89, 97}; // Array of integers
int low, high, mid, flag = 0; // Variables for binary search and flag for checking if element is found
void display(int n) {
low = 0; // Initialize low to the first index
high = A.length - 1; // Initialize high to the last index
while (low <= high) {
mid = (low + high) / 2; // Calculate mid index
if (n == A[mid]) { // If the element is found
flag = 1;
break;
} else if (n > A[mid]) { // If the search element is greater, ignore the left half
low = mid + 1;
} else { // If the search element is smaller, ignore the right half
high = mid - 1;
}
}
if (flag == 1) {
System.out.println(n + " found at position " + (mid + 1)); // Element found
} else {
System.out.println("Search element not found"); // Element not found
}
}
public static void main(String args[]) {
BSearch obj = new BSearch();
obj.display(15); // Test the binary search with the element 15
}
}
15 found at position 5
Array Initialization:
int A[] = {5, 7, 9, 11, 15, 20, 30, 45, 89, 97}; defines the array of integers to be searched.Binary Search Logic:
low, high, and mid variables help in narrowing down the search range.A[mid]) with the target (n). Depending on whether n is greater or lesser, the search range is adjusted by modifying low or high.Flag for Element Found:
flag = 1; indicates that the element has been found, which breaks the loop.Output:
15 in the array, but you can modify obj.display(15); to search for any other integer.First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.