Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Following the instructions given in the textbook and the accompanying website on how to compile and run Java programs, write two well-documented (commented) programs named

Following the instructions given in the textbook and the accompanying website on how to compile and run Java programs, write two well-documented (commented) programs named as required (see below), and make one submission of the assignment with separate file attachments for each program; therefore, for this assignment, there will be two attachments. Each attached file will be a java program with a file name of program name.java.

1. Modify the BinarySearch program given in the textbook (program 4.2.3) so that if the search key is in the array, it returns the largest index i for which a[i] is equal to key, but, otherwise, returns i where i is the largest index such that a[i] is less than key. It should also be modified to deal with integer arrays rather than string arrays. [MO5.2, MO5.3]

Note: The program should take two command-line arguments, (1) an input file that contains a sorted integer array; and (2) an integer to search for in that array.

  • Sample runs would be as follows. >more input.txt 2 3 4 5 6 6 6 7 8 9 11 >java BinarySearch input.txt 10 -9 >java BinarySearch input.txt 6 6

Program 4.2.3 Binary search (sorted array)

public class BinarySearch

{

public static int search (String key, String [] a)

{return search (key, a, 0 ,a.length);}

public static int search ( string key , string [] a, int lo, int hi)

{ if (hi< = lo) return -1 ;

int mid = lo + (hi-lo)/ 2;

int cmp= a[mid].compareTo(key);

if (cmd >0) return search (key , a, lo, mid);

else if (cmd<0) return search (key, a, mid+1, hi);

else return mid;

}

public static void main(string[] args)

{

In in = new in(args[0]);

String []a=in.readAllstrings();

while (!StdIn.isEmpty())

{ string key = StdIn.readString();

if (search(key, a)<0) Stdout.println(key);

}

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions