Skip to content
Open
Show file tree
Hide file tree
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
36 changes: 36 additions & 0 deletions BinarySearch.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
public class BinarySearch {

// Time Complexity: O(log n)
// Space Complexity: O(1)
// Note: Array must be sorted

public static int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;

while (left <= right) {
int mid = left + (right - left) / 2;

if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}

public static void main(String[] args) {
int[] arr = {2, 4, 6, 8, 10};
int target = 8;

int result = binarySearch(arr, target);

if (result != -1) {
System.out.println("Element found at index " + result);
} else {
System.out.println("Element not found ");
}
}
}
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# Programming_Hactoberfest23
New Contribution Repository
https://github.com/Nikhil-2002/hacktoberfest2025-contributions

### Java Algorithms
- Binary Search (BinarySearch.java)