Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement a generic version of the binary search algorithm /** A class for execu

ID: 3762251 • Letter: I

Question

Implement a generic version of the binary search algorithm

/**
A class for executing binary searches through an array.
*/
public class BinarySearcher
{
private int[] a;

/**
Constructs a BinarySearcher.
@param anArray a sorted array
*/
public BinarySearcher(int[] anArray)
{
a = anArray;
}

/**
Finds a value in a sorted array, using the binary
search algorithm.
@param v the value to search
@return the index at which the value occurs, or -1
if it does not occur in the array
*/
public int search(int v)
{
int low = 0;
int high = a.length - 1;
while (low <= high)
{
int mid = (low + high) / 2;
int diff = a[mid] - v;

if (diff == 0) // a[mid] == v
return mid;
else if (diff < 0) // a[mid] < v
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
}

Explanation / Answer

import java.util.ArrayList; public class BinarySearcher { private T[] a; public BinarySearcher(T[] words) { a = words; } public int search(Comparable v) { int low = 0; int high = a.length - 1; while (low 0) { low = mid + 1; } else { return mid; } } return -1; } }
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote