please help me with this question. Java r9 Sorting and Searching Arrays 6. Phone
ID: 3741104 • Letter: P
Question
please help me with this question. Java
r9 Sorting and Searching Arrays 6. Phone Number Lookup Recall that Programming Exercise 7 in Chapter 8 asked you to design a program with two parallel arrays: a string array named people and a String array named phonexumbers. The program allows you to search for a person's name in the people array. If the name is found, it displays that person's phone numbe Modify the program so it uses the binary search algorithm instead of the sequen- tial search algorithm. r. 686169000-ETOExplanation / Answer
package contact;
import java.util.Scanner;
class Contact{
String name[];
String phonenumber[];
String Str;
int number;
Contact()
{
int i;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of records:");
number=sc.nextInt();
name=new String[number];
phonenumber=new String[number];
for(i=0;i<number;i++)
{
System.out.print(" Enter the name of "+(i+1)+"Person:");
name[i]=sc.next();
System.out.print(" Enter the contact of "+(i+1)+"Person:");
phonenumber[i]=sc.next();
}
Str= new String();
System.out.println(" Enter the name to be search:");
Str=sc.next();
sc.close();
}
void sort()
{
int i,j,index;
String str=new String();
for(i=0;i<number-1;i++)
{
index=i;
for(j=i+1;j<number;j++)
if(name[index].compareTo(name[j])>0)
index=j;
if(index!=j)
{
str=name[index];
name[index]=name[i];
name[i]=str;
str=phonenumber[index];
phonenumber[index]=phonenumber[i];
phonenumber[i]=str;
}
}
}
void display()
{
int i;
System.out.println("Status: ");
for(i=0;i<number;i++)
System.out.println("Name:"+name[i]+" Contact"+phonenumber[i]);
}
void binarysearch()
{
int beg,end, mid,k;
beg=0;
end=number;
while(beg<end)
{
mid=(beg+end)/2;
k= name[mid].compareTo(Str);
if(k==0)
{
System.out.println(" Record found: "+"Name:"+name[mid]+" Contact"+phonenumber[mid]);
break;
}
if(k<0)
end=mid-1;
else
beg=mid+1;
}
}
}
public class Main {
public static void main(String[] args) {
Contact C= new Contact();
C.sort();
C.display();
C.binarysearch();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.