Write a Java program that contains the following methods: 1) public static int l
ID: 3615174 • Letter: W
Question
Write a Java program that contains the following methods:1) public static int linearSearch (String [ ] strArray, StringstrValue )
If strValue is found in the array, return the index where strValuewas found. If not found, return -1.
Check each element to make sure it is not NULL before comparing itto strValue.
2) public static int binarySearch (String [ ] strArray, StringstrValue )
If strValue is found in the array, return the index where strValuewas found. If not found, return -1.
Check each element to make sure it is not NULL before comparing itto strValue.
3) public static void printStringArray (String [ ] strArray)
Print only the non-NULL elements of the array, one per line.
Explanation / Answer
import java.util.*;
publicclass Test {
publicstatic voidmain(String args[])
{
String[]s=new String[4];
s[0]="hello";s[1]="hello2";s[2]="hello3";s[3]="hello4";
System.out.println("It is found at :" + linearSearch(s,"hello4"));
System.out.println("It is found at :" + binarySearch(s,"hello3"));
}
publicstatic intbinarySearch (String [ ] strArray, String strValue)
{
int i,n,mid,low=0,high=strArray.length-1;
mid = (low+high)/2;
while(true)
{
if(strValue == strArray[mid])
return mid;
if(strArray[mid].compareTo(strValue) < 0)
{
low=mid;
}else
high=mid;
n=mid;
mid= (low+high)/2;
if(n==mid)
break;
}
return -1;
}
publicstatic voidprintStringArray (String [ ] strArray)
{
int i;
for(i=0;i<strArray.length;i++)
System.out.println(strArray[i]);
}
publicstatic intlinearSearch (String [] strArray, String strValue)
{
int n=0;
for(n=0;n<strArray.length;n++)
if(strValue==strArray[n])
return n;
return -1;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.