Write a java program fills in an array with up to 20 nonnegative whole numbers a
ID: 3824661 • Letter: W
Question
Write a java program fills in an array with up to 20 nonnegative whole numbers and the searches the array for values specifid by the user.
I would like to see that you are using binary searsh:
- Implemented by while loop
-implemened by recursion
in the same main
by using this code for while loop:
static int BinarySearch(char target, char array[]) {
int low=0, high = 19, middle;
while( low<=high) {
middle = (low+high)/2;
if( array[middle]==target )
return middle;
else if( array[middle]<target )
low = middle + 1;
else
high = middle - 1;
}
return -1;
}
and this code for recursion:
static int BinarySearch(char target, int low, int high, char[] array) {
if( target<array[low] || target>array[high] )
return -1;
int middle = (low+high)/2;
if( array[middle]==target )
return middle;
else if( array[middle]>target )
return BinarySearch(target, low, middle-1, array);
else
return BinarySearch(target, middle+1, high, array);
}
Explanation / Answer
Here is the code for you:
import java.util.*;
class BinarySearchVersions
{
public static int BinarySearchIterative(int target, int array[])
{
int low=0, high = 19, middle;
while( low<=high)
{
middle = (low+high)/2;
if( array[middle]==target )
return middle;
else if( array[middle]<target )
low = middle + 1;
else
high = middle - 1;
}
return -1;
}
public static int BinarySearchRecursive(int target, int low, int high, int[] array)
{
if( target<array[low] || target>array[high] )
return -1;
int middle = (low+high)/2;
if( array[middle]==target )
return middle;
else if( array[middle]>target )
return BinarySearchRecursive(target, low, middle-1, array);
else
return BinarySearchRecursive(target, middle+1, high, array);
}
public static void main(String[] args)
{
//fills in an array with up to 20 nonnegative whole numbers
int[] array = new int[20];
System.out.print("Enter 20 non-negative values: ");
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 20; i++)
{
array[i] = sc.nextInt();
if(array[i] < 0)
{
System.out.print("Negative values are not allowed. Please re-enter: ");
i--;
}
}
System.out.print("Enter a search key to search from: ");
int key = sc.nextInt();
int pos = BinarySearchIterative(key, array);
if(pos == -1)
System.out.println("Element not found in the list.");
else
System.out.println("Element found at index: " + pos);
pos = BinarySearchRecursive(key, 0, 19, array);
if(pos == -1)
System.out.println("Element not found in the list.");
else
System.out.println("Element found at index: " + pos);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.