Question

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 Improve this question Transcribed image text
Request Professional Answer

Request Answer!

We need at least 10 more requests to produce the answer.

0 / 10 have requested this problem solution

The more requests, the faster the answer.

Request! (Login Required)


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 Coins

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>>...

  • FOR JAVA: Summary: Create a program that adds students to the class list (see below). The...

    FOR JAVA: Summary: Create a program that adds students to the class list (see below). The solution should be named Roster402_v2.java. Allow the user to control the number of students added to the roster. Ask if the user would like to see their new roster to confirm additions. If yes, then display contents of the file, if no, end the program. ------------------------------------------------------------------------------------- List of student names and IDs for class (this will be your separate text file): Jones, Jim,45 Hicks,...

  • 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...

  • In Java: Executable Class create an array of Employee objects. You can copy the array you...

    In Java: Executable Class create an array of Employee objects. You can copy the array you made for Chapter 20. create an ArrayList of Employee objects from that array. use an enhanced for loop to print all employees as shown in the sample output. create a TreeMap that uses Strings for keys and Employees as values. this TreeMap should map Employee ID numbers to their associated Employees. process the ArrayList to add elements to this map. print all employees in...

  • //Generic interface that describes various searching and sorting //algorithms. Note that the type parameter is unbounded....

    //Generic interface that describes various searching and sorting //algorithms. Note that the type parameter is unbounded. However, //for these algorithms to work correctly, the data objects must //be compared using the method compareTo and equals. //In other words, the classes implementing the list objects //must implement the interface Comparable. The type parameter T //is unbounded because we would like to use these algorithms to //work on an array of objects as well as on objects of the classes //UnorderedArrayList and...

  • 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 [email protected] 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...

ADVERTISEMENT
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.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT