Problem:
Write a java program that uses binary search to search array
using Comparable in Java
using Comparable in Java
Output:
Not applicable.
Solution:
public class Linearsearch
{
public static void main(String[] args)
{
String[] stuff={"a","b","c"};
System.out.println(linearsearch(stuff,"b", 0));
System.out.println(binarysearch(stuff,"a", 0, stuff.length-1));
}
public static int linearsearch(Comparable[] items, Comparable target, int posfirst)
{
if(posfirst==items.length)
return -1;
else if(items[posfirst].compareTo(target)==0)
{
return posfirst;
}
else
return linearsearch(items, target, (posfirst+1));
}
No comments :
Post a Comment