Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions src/com/Binarysearch.java
Original file line number Diff line number Diff line change
@@ -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");
}
}
}