Skip to content

jUnit Test on Binary Search Algorithm #2

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

Merged
merged 1 commit into from
Feb 20, 2022
Merged
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
73 changes: 73 additions & 0 deletions TestBinarySearch2
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
public class BinarySearch {

/**
* Searches an element {@param n} in a sorted array {@param a}
* and returns its index in O(log n) time. The Index may not
* correspond to the first occurrence of the element.
*
* @param a sorted array to be searched
* @param n number to be searched in the array
* @return index of {@param n} or {@code -1} if not present
*/
public static int binarySearch(int[] a, int n) {
return binarySearch(a, n, 0, a.length - 1);
}

public static int binarySearch(int[] a, int n, int low, int high) {

if (low <= high) {
int mid = (low + high) / 2; // to prevent overflow you can instead do: mid = low + (high - low) / 2

if (n == a[mid]) {
return mid;
} else if (n < a[mid]) {
return binarySearch(a, n, 0, mid - 1);
} else {
return binarySearch(a, n, mid + 1, high);
}
} else {
return -1;
}
}

/**
* Non-recursive version of binary search.
*
* @param a sorted array to be searched
* @param n number to be searched in the array
* @return index of {@param n} or {@code -1} if not present
*/
public static int binarySearchNonRecursive(int[] a, int n) {
int low = 0, high = a.length, mid;
while (low <= high) {
mid = (low + high) / 2; // to prevent overflow you can instead do: mid = low + (high - low) / 2
if (n == a[mid]) {
return mid;
} else if (n < a[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}

/**
* Driver for testing.
*
* @param a
*/
public static void main(String[] args) {
System.out.println(binarySearch(new int[]{0, 2}, 2));
System.out.println(binarySearch(new int[]{0, 1, 2, 3}, 2));
System.out.println(binarySearch(new int[]{0, 1, 2, 3}, 3));
System.out.println(binarySearch(new int[]{0, 2}, 0));
System.out.println(binarySearch(new int[]{0, 1, 2, 2, 2, 3, 3}, 2)); // doesn't return index of first occurrence
System.out.println("---------");
System.out.println(binarySearchNonRecursive(new int[]{0, 2}, 2));
System.out.println(binarySearchNonRecursive(new int[]{0, 1, 2, 3}, 2));
System.out.println(binarySearchNonRecursive(new int[]{0, 1, 2, 3}, 3));
System.out.println(binarySearchNonRecursive(new int[]{0, 2}, 0));
System.out.println(binarySearchNonRecursive(new int[]{0, 1, 2, 2, 2, 3, 3}, 2));
}
}