diff --git a/src/com/Binarysearch.java b/src/com/Binarysearch.java new file mode 100644 index 0000000..37cf4e9 --- /dev/null +++ b/src/com/Binarysearch.java @@ -0,0 +1,63 @@ +import java.util.*; +import java.util.Arrays; + +public class BinarySearch { + + // Iterative version + public static int binarySearchIterative(int[] arr, int target) { + int low = 0; + int high = arr.length - 1; + + while (low <= high) { + // mid calculation avoiding overflow + int mid = low + (high - low) / 2; + + if (arr[mid] == target) { + return mid; // found target + } else if (arr[mid] < target) { + low = mid + 1; // search right half + } else { + high = mid - 1; // search left half + } + } + + return -1; // target not found + } + + // Recursive version + public static int binarySearchRecursive(int[] arr, int low, int high, int target) { + if (low <= high) { + int mid = low + (high - low) / 2; + + if (arr[mid] == target) { + return mid; + } else if (arr[mid] < target) { + return binarySearchRecursive(arr, mid + 1, high, target); + } else { + return binarySearchRecursive(arr, low, mid - 1, target); + } + } + return -1; // not found + } + + public static void main(String[] args) { + int[] sortedArray = {2, 4, 6, 8, 10, 12, 14}; + int target = 10; + + // Using iterative method + int resultIter = binarySearchIterative(sortedArray, target); + if (resultIter != -1) { + System.out.println("Iterative: Target found at index " + resultIter); + } else { + System.out.println("Iterative: Target not found"); + } + + // Using recursive method + int resultRec = binarySearchRecursive(sortedArray, 0, sortedArray.length - 1, target); + if (resultRec != -1) { + System.out.println("Recursive: Target found at index " + resultRec); + } else { + System.out.println("Recursive: Target not found"); + } + } +}