Homework Help Question & Answers

The file Sorting.java contains the Sorting class from Listing 9.9 in the text. This class implements...

The file Sorting.java contains the Sorting class from Listing 9.9 in the text. This class implements both the selection sort and the insertion sort algorithms for sorting any array of Comparable objects in ascending order. In this exercise, you will use the Sorting class to sort several different types of objects.

1. The file Numbers.java reads in an array of integers, invokes the selection sort algorithm to sort them, and then prints the sorted array. Save Sorting.java and Numbers.java to your directory.

Numbers.java won't compile in its current form. Study it to see if you can figure out why.

2. Try to compile Numbers.java and see what the error message is. The problem involves the difference between primitive data and objects. Change the program so it will work correctly (note: you don't

need to make many changes - the autoboxing feature of Java 1.5 will take care of most conversions from int to Integer).

3. Write a program Strings.java, similar to Numbers.java, that reads in an array of String objects and sorts them. You may just copy and edit Numbers.java.

4. Modify the insertionSort algorithm so that it sorts in descending order rather than ascending order. Change Numbers.java and Strings.java to call insertionSort rather than selectionSort. Run both to

make sure the sorting is correct.

5. The file Salesperson.java partially defines a class that represents a sales person. This is very similar to the Contact class in Listing 9.10. However, a sales person has a first name, last name, and a total number of sales (an int) rather than a first name, last name, and phone number. Complete the compareTo method in the Salesperson class. The comparison should be based on total sales; that is, return a negative number if the executing object has total sales less than the other object and return a positive number if the sales are greater. Use the name of the sales person to break a tie (alphabetical order).

6. The file WeeklySales.java contains a driver for testing the compareTo method and the sorting (this is similar to Listing 9.8 in the text). Compile and run it. Make sure your compareTo method is

correct. The sales staff should be listed in order of sales from most to least with the four people having the same number of sales in reverse alphabetical order.

7. OPTIONAL: Modify WeeklySales.java so the salespeople are read in rather than hardcoded in the program.

//********************************************************************

// Sorting.java       Author: Lewis/Loftus

//

// Demonstrates the selection sort and insertion sort algorithms.

//********************************************************************

public class Sorting

{

   //-----------------------------------------------------------------

   // Sorts the specified array of objects using the selection

   // sort algorithm.

   //-----------------------------------------------------------------

   public static void selectionSort (Comparable[] list)

   {

      int min;

      Comparable temp;

      for (int index = 0; index < list.length-1; index++)

      {

         min = index;

         for (int scan = index+1; scan < list.length; scan++)

            if (list[scan].compareTo(list[min]) < 0)

               min = scan;

         // Swap the values

         temp = list[min];

         list[min] = list[index];

         list[index] = temp;

      }

   }

   //-----------------------------------------------------------------

   // Sorts the specified array of objects using the insertion

   // sort algorithm.

   //-----------------------------------------------------------------

   public static void insertionSort (Comparable[] list)

   {

      for (int index = 1; index < list.length; index++)

      {

         Comparable key = list[index];

         int position = index;

         // Shift larger values to the right

         while (position > 0 && key.compareTo(list[position-1]) < 0)

         {

            list[position] = list[position-1];

            position--;

         }

         list[position] = key;

      }

   }

}

// ******************************************************

//   Numbers.java

//

//   Demonstrates selectionSort on an array of integers.

// ******************************************************

import java.util.Scanner;

public class Numbers

{

    // --------------------------------------------

    // Reads in an array of integers, sorts them,

    // then prints them in sorted order.

    // --------------------------------------------

    public static void main (String[] args)

   {

        int[] intList;

        int size;

        Scanner scan = new Scanner(System.in);

        System.out.print ("\nHow many integers do you want to sort? ");

        size = scan.nextInt();

        intList = new int[size];

        System.out.println ("\nEnter the numbers...");

        for (int i = 0; i < size; i++)

            intList[i] = scan.nextInt();

        Sorting.selectionSort(intList);

        System.out.println ("\nYour numbers in sorted order...");

        for (int i = 0; i < size; i++)

            System.out.print(intList[i] + " ");

        System.out.println ();

    }

}

// *******************************************************

//   Salesperson.java

//

//   Represents a sales person who has a first name, last

//   name, and total number of sales.

// *******************************************************

public class Salesperson implements Comparable

{

    private String firstName, lastName;

    private int totalSales;

    //------------------------------------------------------

   // Constructor: Sets up the sales person object with

    //                the given data.

    //------------------------------------------------------

    public Salesperson (String first, String last, int sales)

    {

        firstName = first;

        lastName = last;

        totalSales = sales;

    }

    //-------------------------------------------

    // Returns the sales person as a string.

    //-------------------------------------------

    public String toString()

    {

        return lastName + ", " + firstName + ": \t" + totalSales;

    }

    //-------------------------------------------

    // Returns true if the sales people have

    // the same name.

    //-------------------------------------------

    public boolean equals (Object other)

    {

        return (lastName.equals(((Salesperson)other).getLastName()) &&

                firstName.equals(((Salesperson)other).getFirstName()));

    }

    //--------------------------------------------------

    // Order is based on total sales with the name

    // (last, then first) breaking a tie.

    //--------------------------------------------------

    public int compareTo(Object other)

    {

        int result;

        return result;

    }

    //-------------------------

    // First name accessor.

    //-------------------------

    public String getFirstName()

    {

        return firstName;

    }

    //-------------------------

    // Last name accessor.

    //-------------------------

    public String getLastName()

    {

        return lastName;

    }

    //-------------------------

    // Total sales accessor.

    //-------------------------

    public int getSales()

    {

        return totalSales;

    }

}

// *************************************************************

//    WeeklySales.java

//

//    Sorts the sales staff in descending order by sales.

// ************************************************************

public class WeeklySales

{

    public static void main(String[] args)

    {

        Salesperson[] salesStaff = new Salesperson[10];

        salesStaff[0] = new Salesperson("Jane", "Jones", 3000);

        salesStaff[1] = new Salesperson("Daffy", "Duck", 4935);

        salesStaff[2] = new Salesperson("James", "Jones", 3000);       

        salesStaff[3] = new Salesperson("Dick", "Walter", 2800);       

        salesStaff[4] = new Salesperson("Don", "Trump", 1570);

        salesStaff[5] = new Salesperson("Jane", "Black", 3000);

        salesStaff[6] = new Salesperson("Harry", "Taylor", 7300);      

        salesStaff[7] = new Salesperson("Andy", "Adams", 5000);

        salesStaff[8] = new Salesperson("Jim", "Doe", 2850);   

        salesStaff[9] = new Salesperson("Walt", "Smith", 3000);

        Sorting.insertionSort(salesStaff);

        System.out.println ("\nRanking of Sales for the Week\n");

        for (Salesperson s : salesStaff)

            System.out.println (s);

    }

}

0 0
Add a comment
Answer

This Homework Help Question: "The file Sorting.java contains the Sorting class from Listing 9.9 in the text. This class implements..." No answers yet.

Be the First!

Request Answer

Request answer!

We need 10 more requests to produce the answer to this homework help question. Share with your friends to get the answer faster!

0 /10 have requested the answer to this homework help question.

Request! (Login Required) Share with friends


Once 10 people have made a request, the answer to this question will be available in 1-2 days.
All students who have requested the answer will be notified once they are available.
Know the answer?
Add Answer to:
The file Sorting.java contains the Sorting class from Listing 9.9 in the text. This class implements...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coin

Coins can be redeemed for fabulous gifts.

Similar Homework Help Questions
  • Modify the sorts (selection sort, insertion sort, bubble sort, quick sort, and merge sort) by adding code to each to tally the total number of comparisons and total execution time of each algorithm. E...

    Modify the sorts (selection sort, insertion sort, bubble sort, quick sort, and merge sort) by adding code to each to tally the total number of comparisons and total execution time of each algorithm. Execute the sort algorithms against the same list, recording information for the total number of comparisons and total execution time for each algorithm. Try several different lists, including at least one that is already in sorted order. ---------------------------------------------------------------------------------------------------------------- /** * Sorting demonstrates sorting and searching on an...

  • Using Merge Sort: (In Java) (Please screenshot or copy your output file in the answer) In...

    Using Merge Sort: (In Java) (Please screenshot or copy your output file in the answer) In this project, we combine the concepts of Recursion and Merge Sorting. Please note that the focus of this project is on Merging and don't forget the following constraint: Programming Steps: 1) Create a class called Art that implements Comparable interface. 2) Read part of the file and use Merge Sort to sort the array of Art and then write them to a file. 3)...

  • Create a program called GeneralizedBubbleSort that will make use of the Comparable Interface in the same...

    Create a program called GeneralizedBubbleSort that will make use of the Comparable Interface in the same way it is used in the GeneralizedSelectionSort. You should use the attached ComparableDemo to test your program. public class ComparableDemo { public static void main(String[] args) { Double[] d = new Double[10]; for (int i = 0; i < d.length; i++) d[i] = new Double(d.length - i); System.out.println("Before sorting:"); int i; for (i = 0; i < d.length; i++) System.out.print(d[i].doubleValue( ) + ", ");...

  • Implement the classes in the following class diagram. The Book class implements the Comparable interface. Use impl...

    Implement the classes in the following class diagram. The Book class implements the Comparable interface. Use implements Comparable<Book> in the class definition. Now, all book objects are instances of the java.lang.Comparable interface. Write a test program that creates an array of ten books. 1. Use Arrays.sort( Book[]l books) from the java.util package to sort the array. The order of objects in the array is determined using compareTo...) method. 2. Write a method that returns the most expensive book in the...

  • Answer please Exercice 3(25+ 20 pts); Sorting 1-Sorting is a classic subject in computer science. There...

    Answer please Exercice 3(25+ 20 pts); Sorting 1-Sorting is a classic subject in computer science. There are many sorting algorithms a. Complete the below code b.Add comments to the below code to explain each statement c. Write a main test then give the output screen of it 2- a-Write the following two generic methods using the below code. The first method sorts the elements using the Comparable interface and the second uses the Comparator interface. public static <E extends Comparable<E>>...

  • Objective: in Java Write a program that implements 3 sorting algorithms and times them in real ti...

    Objective: in Java Write a program that implements 3 sorting algorithms and times them in real time. These algorithms will sort Cylinders by their volume. First, download the driver and include it in your project. Write a class Cylinder with the following properties baseRadius: a non-negative number that corresponds to the Cylinder’s base’s radius. height: a non-negative number that corresponds to the Cylinder’s height. Next, write a class Sorter with the following bubbleSort: This static method takes in an array...

  • Can someone compile this and name the it A4MA5331550.java and compile to make .class file. Will...

    Can someone compile this and name the it A4MA5331550.java and compile to make .class file. Will need to name . class file A4MA5331550 also when done put both files in a zipped folder named A4MA5331550 and email the folder to ensaye@gmail.com here is the program: import java.util.Scanner; /** * 09/17/2017 * Dakota Mammedaty * MA5331550 * Bubble sorted */ public class MA5331550 { public static void main(String[] args) throws IOException { Sort st =new Sort(); st.getData(); System.out.println("=================Sorting Algorithms================="); System.out.println("1. Bubble...

  • Directions: Follow the instructions below to explore sorting objects using boxes below. You will sort the...

    Directions: Follow the instructions below to explore sorting objects using boxes below. You will sort the boxes by the largest volume. Copy and Paste the Box method below into BlueJ public class Box { private double length, height, depth;    public Box( double length, double height, double depth ) { this.length = length; this.height = height; this.depth = depth; }    public double volume() { return length*height*depth; } // compare this Box to another Box int compareTo( Box other )...

  • Here is the code from the previous three steps: #include <iostream> using namespace std; class Student...

    Here is the code from the previous three steps: #include <iostream> using namespace std; class Student { private: //class variables int ID; string firstName,lastName; public: Student(int ID,string firstName,string lastName) //constructor { this->ID=ID; this->firstName=firstName; this->lastName=lastName; } int getID() //getter method { return ID; } virtual string getType() = 0; //pure virtual function virtual void printInfo() //virtual function to print basic details of a student { cout << "Student type: " << getType() << endl; cout << "Student ID: " << ID...

  • CSC110 Lab 6 (ALL CODING IN JAVA) Problem: A text file contains a paragraph. You are to read the contents of the file, store the UNIQUEwords and count the occurrences of each unique word. When the fil...

    CSC110 Lab 6 (ALL CODING IN JAVA) Problem: A text file contains a paragraph. You are to read the contents of the file, store the UNIQUEwords and count the occurrences of each unique word. When the file is completely read, write the words and the number of occurrences to a text file. The output should be the words in ALPHABETICAL order along with the number of times they occur and the number of syllables. Then write the following statistics to...

Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.