Write Java code for the Binary search algorithm. Make sure to use generics. Now
ID: 3703543 • Letter: W
Question
Write Java code for the Binary search algorithm. Make sure to use generics. Now create an appropriate class to represent a circle. show that you can use your generic Binary search to search for a circle in an array of circles based on the radii Write Java code for the Binary search algorithm. Make sure to use generics. Now create an appropriate class to represent a circle. show that you can use your generic Binary search to search for a circle in an array of circles based on the radii Write Java code for the Binary search algorithm. Make sure to use generics. Now create an appropriate class to represent a circle. show that you can use your generic Binary search to search for a circle in an array of circles based on the radii Write Java code for the Binary search algorithm. Make sure to use generics. Now create an appropriate class to represent a circle. show that you can use your generic Binary search to search for a circle in an array of circles based on the radiiExplanation / Answer
import java.util.Arrays;
public class BinarySearch{
public static <T extends Comparable<T>> int search(T[] arr,T value, int low, int high ){
if(low>high)
return -1;
int mid = low+(high-low)/2;
int comp=value.compareTo(arr[mid]);
if(comp<0)
return search(arr,value,low,mid-1);
else if(comp>0)
return search(arr,value,mid+1,high);
else
return mid;
}
public static <T extends Comparable<T>> void swap(T[] arr,int left,int right)
{
T temp=arr[left];
arr[left]=arr[right];
arr[right]=temp;
}
public static void main(String args[]){
Integer arr[]={2,12,34,1,6};
Arrays.sort(arr);
BinarySearch bs=new BinarySearch();
Integer k=12;
int key=BinarySearch.<Integer>search(arr,k,0,arr.length-1);
System.out.println(key);
}
}
You can include Console Reading using Scanner to this Program.
Also, the defult values can be changed with vaues of your wish of any data type. But, don't forget to use Class data types but not primitive types.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.