Question

IN JAVA Iterative Linear Search, Recursive Binary Search, and Recursive Selection Sort: <-- (I need the...

IN JAVA

Iterative Linear Search, Recursive Binary Search, and Recursive Selection Sort: <-- (I need the code to be written with these)

I need Class river, Class CTRiver and Class Driver with comments so I can learn and better understand the code I also need a UML Diagram HELP Please!

Class River describes river’s name and its length in miles. It provides accessor methods (getters) for both variables, toString() method that returns String representation of the river, and method isLong() that returns true if river is above 30 miles long and returns false otherwise.

Class CTRivers describes collection of CT rivers. It has no data, and it provides the following service methods. None of the methods prints anything, except method printLongRiversRec, which prints all long rivers. Input parameter n in all methods is number of occupied elements in the list.

// Prints all long rivers in the list. Print them in same order as they were in the list . List can be

// empy or not.

  • void printLongRiversRec(River[] list, int n)

// Returns index for the river object with given name. Returns -1 for unsuccessful search. List can

// be empy or not.

  • int linearSearch(River[] list, int n, String name)

// Returns ArrayList of rivers with length between min and max inclusive. If no such river was found,

// method returns an empty Arraylist. List can be empy or not.

  • ArrayList searchRange(River[] list, int n, int min, int max)

// Sorts list of rivers by comparing them by names. Apply selection sort recursively. List of rivers can be

// empy or nonempty. Empty list and list with one river only are sorted. Lists with two or more rivers are

// sorted by swapping last river in the list with river object that has name that is last in lexicographic order // in the array, and after that recursively sorting sublist of first n-1 rivers.

  • void sortByNameRec(River[] list, int n)

// PRECONDITION: Method assumes that input list is sorted by names. First and last are indices of the first

// and last river of the current sublist. Method returns index of river object with given name or returns -1

// if none of the rivers has that name. List of rivers can be empy or not.

  • int binarySearchRec(River[] list, int first, int last, String name)

The three methods highlighted in yellow must be implemented recursively.

File “input.txt”

Naugatuck   40

Pawcatuck   34

Quinebaug   69

Shepaug   26

Connecticut   407

Still   25

Quinnipiac   46

Housatoic 139

Class Driver has main method in it. Read data from the input file "input.txt" into an array of River objects, named riverList, and keep track of number of rivers stored in variable counter. Array riverList has capacity 100. Input file should be as shown. Program should work for any input file with up to 100 rivers in it.

  • Print all long rivers.
  • Apply one successful and one unsuccessful linear search.
  • Print all rivers with length between min and max (min and max are provided by user). Must use for each loop in the main method to print resulting ArrayList returned by method searchRange .
  • Sort myList by river names, and print sorted list.
  • Apply one successful and one unsuccessful binary search on sorted list.

Must print appropriate explanation in English of all steps performed in outcome.

Need a picture of the UML Diagram as well

Homework Answers

Answer #1

SOLUTION-
I have solve the problem in Java code with comments and screenshot for easy understanding :)

CODE-

River.java
public class River
{
private String name;
private int length;

public River(String name, int length) {
this.name = name;
this.length = length;
}

public String getName() {
return name;
}

public int getLength() {
return length;
}

@Override
public String toString()
{
String str = String.format("%-12s %10d",name,length);
return str;
}
  
  
}

CTRiver.java


import java.util.ArrayList;


public class CTRivers
{
public void printListRec(River[] list, int n)
{
for(int i=0;i<n;i++)
System.out.println(list[i]);
}
public int linearSearch(River[] list, int n, String name)
{
for(int i=0;i<n;i++)
{
if(list[i].getName().equalsIgnoreCase(name))
return i;
}
return -1;
}
public ArrayList <River> searchRange(River[] list, int n, int min, int max)
{
ArrayList <River> riverList=new ArrayList<>();
for(int i=0;i<n;i++)
{
if(list[i].getLength()>=min && list[i].getLength()<=max)
riverList.add(list[i]);
}
return riverList;
}
public void sortByNameRec(River[] list, int n)
{
selectionSort(list,0,n);
}
//these are the helper function
private static void swap(River[] arr, int i, int j)
{
River temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Recursive function to perform selection sort on sub-array arr[i..n-1]
private static void selectionSort(River[] arr, int i, int n)
{
// find the minimum element in the unsorted sub-array[i..n-1]
// and swap it with arr[i]
int min = i;
for (int j = i + 1; j < n; j++)
{
// if arr[j] element is less, then it is the new minimum
if (arr[j].getName().compareTo( arr[min].getName() ) < 0)
{
min = j; // update index of min element
}
}
// swap the minimum element in sub-array[i..n-1] with arr[i]
swap(arr, min, i);
if (i + 1 < n)
{
selectionSort(arr, i + 1, n);
}
}
River binarySearchRec(River[] list, int n, String name)
{
int index=binarySearch(list, 0, n-1, name);
if(index!=-1)
return list[index];
return null;
}
private static int binarySearch(River arr[], int l, int r, String x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
  
// If the element is present at the middle itself
if (arr[mid].getName().equals(x))
return mid;
  
// If element is smaller than mid, then it can only
// be present in left subarray
if ((arr[mid].getName().compareTo(x))<0)
return binarySearch(arr, l, mid - 1, x);
  
// Else the element can only be present in right
// subarray
return binarySearch(arr, mid + 1, r, x);
}
  
// We reach here when element is not present in array
return -1;
}
public void insertInOrder(River[] list, int n, River river)
{
int i=0;
for(i=0;i<n;i++)
{
if(list[i].getName().compareTo(river.getName())>0)
break;
}
for(int j=n; j > i; j--)
{
list[j] = list[j-1];
}
list[i] = river;
}
}

Driver.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;


public class Driver {

/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
BufferedReader reader;
River []MyList=new River[100];
CTRivers ctObject=new CTRivers();
int count=0;
try
{
reader = new BufferedReader(new FileReader("input.txt"));
String line = reader.readLine();
while (line != null)
{
String[] splited = line.split(" ");
MyList[count]=new River(splited[0],Integer.parseInt(splited[1]));
line = reader.readLine();
count++;
}
reader.close();
} catch (IOException e)
{
e.printStackTrace();
}
System.out.printf("%-7s %15s\n","River Name","Length");
ctObject.printListRec(MyList, count);
int index=ctObject.linearSearch(MyList, count, "Quinnipiac");
  
System.out.println("\n\nUsing linear search\n");
if(index>=0)
System.out.println("Quinnipiac is in the array at location :"+index);
  
index=ctObject.linearSearch(MyList, count, "Ganga");
if(index>=0)
System.out.println("Ganga is in the array at location :"+index);
else
System.out.println("Ganga is not in the array");
  
ctObject.sortByNameRec(MyList, count);
System.out.println("\n\nAfter sorting\n");
System.out.printf("%-7s %15s\n","River Name","Length");
ctObject.printListRec(MyList, count);
  
System.out.println("\n\nUsing binary search\n");
  
River r=ctObject.binarySearchRec(MyList, count, "Pawcatuck");
  
if(r==null)
System.out.println("Pawcatuck is not available in the list");
else
System.out.println("Pawcatuck is available in the list");
  
r=ctObject.binarySearchRec(MyList, count, "Jamuna");
  
if(r==null)
System.out.println("Jamuna is not available in the list");
else
System.out.println("Jamuna is available in the list");
  
ctObject.insertInOrder(MyList, count, new River("Farmington",47));
count++;
ctObject.insertInOrder(MyList, count, new River("Ganga",187));
count++;
  
System.out.println("\n\nAfter adding 2 new river the list is :");
ctObject.printListRec(MyList, count);
  
}
  
}


SCREENSHOT-

IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I WILL SOLVE IT FOR YOU:)
----------------PLEASE RATE THE ANSWER-----------THANK YOU!!!!!!!!----------

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Java : Modify the selection sort algorithm to sort an array of integers in descending order....
Java : Modify the selection sort algorithm to sort an array of integers in descending order. describe how the skills you have gained could be applied in the field. Please don't use an already answered solution from chegg. I've unfortunately had that happen at many occasion ....... ........ sec01/SelectionSortDemo.java import java.util.Arrays; /** This program demonstrates the selection sort algorithm by sorting an array that is filled with random numbers. */ public class SelectionSortDemo { public static void main(String[] args) {...
You are given a reference to the root node of a binary search tree, that implements...
You are given a reference to the root node of a binary search tree, that implements a dictionary data structure. Please print all the elements in depths 500 through 510, all in sorted order. A node in a binary search tree is at depth x, if it takes x hops to get from the root. So the root is at depth 0, the children of the root are at depth 1, and so on. The class TreeNode defines a single...
language: JAVA the Problem Below are a series of problems you need to solve using recursive...
language: JAVA the Problem Below are a series of problems you need to solve using recursive methods. You will write a program that will read commands from an input file, with each command referring to one of the recursive problems to be executed. Each command will be followed (on the same line of input) by the respective parameters required for that problem. (15 points for main method) DescArrayCheck   Write a recursive method that checks whether an array of integers -...
<<<<<<<< I need only the UML diagram for ALL classes.Java???????????? public class House {    private...
<<<<<<<< I need only the UML diagram for ALL classes.Java???????????? public class House {    private int houseNumber;    private int bedrooms;    private int sqFeet;    private int year;    private int cost;    public House(int houseNumber,int bedrooms,int sqFeet, int year, int cost)    {        this.houseNumber = houseNumber;        this.bedrooms = bedrooms;        this.sqFeet = sqFeet;        this.year = year;        this.cost = cost;    }    public int getHouseNumber()    {        return houseNumber;    }   ...
Write code in java Implement a method to build an AVL tree out of a sorted...
Write code in java Implement a method to build an AVL tree out of a sorted (ascending order) array of unique integers, with the fastest possible big O running time. You may implement private helper methods as necessary. If your code builds a tree that is other than an AVL tree, you will not get any credit. If your code builds an AVL tree, but is not the fastest big O implementation, you will get at most 12 points. You...
[Java] I'm not sure how to implement the code. Please check my code at the bottom....
[Java] I'm not sure how to implement the code. Please check my code at the bottom. In this problem you will write several static methods to work with arrays and ArrayLists. Remember that a static method does not work on the instance variables of the class. All the data needed is provided in the parameters. Call the class Util. Notice how the methods are invoked in UtilTester. public static int min(int[] array) gets the minimum value in the array public...
Please answer in JAVA IDS 401 Assignment 4 Deadline In order to receive full credit, this...
Please answer in JAVA IDS 401 Assignment 4 Deadline In order to receive full credit, this assignment must be submitted by the deadline on Blackboard. Submitting your assignment early is recommended, in case problems arise with the submission process. Late submissions will be accepted (but penalized 10pts for each day late) up to one week after the submission deadline. After that, assignments will not be accepted. Assignment The object of this assignment is to construct a mini-banking system that helps...
In this lab, you will write a program that creates a binary search tree based on...
In this lab, you will write a program that creates a binary search tree based on user input. Then, the user will indicate what order to print the values in. **Please write in C code** Start with the bst.h and bst.c base code provided to you. You will need to modify the source and header file to complete this lab. bst.h: #ifndef BST_H #define BST_H typedef struct BSTNode { int value; struct BSTNode* left; struct BSTNode* right; } BSTNode; BSTNode*...
I need this before the end of the day please :) In Java 10.13 Lab 10...
I need this before the end of the day please :) In Java 10.13 Lab 10 Lab 10 This program reads times of runners in a race from a file and puts them into an array. It then displays how many people ran the race, it lists all of the times, and if finds the average time and the fastest time. In BlueJ create a project called Lab10 Create a class called Main Delete what is in the class you...
You can complete this assignment individually or as a group of two people. In this assignment...
You can complete this assignment individually or as a group of two people. In this assignment you will create a ​​Sorted Singly-Linked List​ that performs basic list operations using C++. This linked list should not allow duplicate elements. Elements of the list should be of type ‘ItemType’. ‘ItemType’ class should have a private integer variable with the name ‘value’. Elements in the linked list should be sorted in the ascending order according to this ‘value’ variable. You should create a...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT