Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Java Binary Search #6810

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
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
3 changes: 3 additions & 0 deletions code/languages/Java/README_binary_search.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Binary search is a method for finding the index of an element in an already-sorted array. It works by repeatedly halving the array, picking the half that contains our element based on whether the middle element is lesser or greater than it, until the element is found. It's one of the simplest examples of a "divide and conquer" algorithm, which is an algorithm that repeatedly reduces the problem into smaller sub-problems until a solution is found.

Binary search runs in O(log n) time.
56 changes: 56 additions & 0 deletions code/languages/Java/binary_search.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
class BinarySearch {
public static int binarySearchInt(int[] arr, int x) {
// Initialize the variables. start and end define our search space
int start = 0;
int end = arr.length - 1;
int midpoint;
// The main loop. Each iteration we cut our search space in half
while (start <= end) {
// Check the midpoint of the search space
midpoint = start + ((end - start)/2);
// If the midpoint is what we're looking for, return
if (arr[midpoint] == x) {
return midpoint;
}
// If the midpoint is too large, search the first half
if (arr[midpoint] > x) {
end = midpoint - 1;
}
// If the midpoint is too small, search the second half
else {
start = midpoint + 1;
}
}
// If we never find the element, it is not in the array. In that case return -1
return -1;
}

public static void intTester() {
int i;
int x;
// The sorted array we will search
int[] sortedArr = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
// A list of numbers not in the array, to see if our function correctly returns -1
int[] extras = {12, -2, 34};

for (i = 0; i < sortedArr.length + extras.length; i += 1) {
if (i < sortedArr.length) {
x = sortedArr[i];
} else {
x = extras[i - sortedArr.length];
}

System.out.print("Searching for element: " + x + "; ");
int result = binarySearchInt(sortedArr, x);
if (result != -1) {
System.out.println("Element found at index: " + result);
} else {
System.out.println("Element not found");
}
}
}

public static void main(String[] args) {
intTester();
}
}