This is java code. How do i change the following two methods to work recursively
ID: 3638003 • Letter: T
Question
This is java code. How do i change the following two methods to work recursively?-------------------------------------------------------------------------------------------------------
public int binarySearch( int value ) {
int low = 0;
int high = count-1;
while (low <= high)
{
int mid = (low+high) / 2;
if (storage[mid] == value)
{
return mid;
}
else if (value < storage[mid])
{
high = mid - 1;
}
else
{
low = mid + 1;
}
numberOfComparisons++;
}
return -1;
-----------------------------------------------------------------------------------------------------
public int linearSearch (int value)
{
for( int i=0; i<count; i++ )
{
if (storage[i] == value)
{
numberOfComparisons++;
return i;
}
}
return -1;
}
Explanation / Answer
public int binarySearch( int value, int low, int high){
if(lowint mid = (low+high)/2;
int mid = (low+high) / 2;
if (storage[mid] == value)
{
return mid;
}
else if (value < storage[mid])
{
return ( binarySearch( value,low,mid-1));
}
else
{
return ( binarySearch( value,mid+1,high));
}
numberOfComparisons++;
}
else
return -1;
}
public int linearSearch (int value, int pos)
{
if(pos<count)
{
if (storage[pos] == value)
{
numberOfComparisons++;
return pos;
}
else
return linearSearch ( value, pos++);
}
else
return -1;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.