Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

20.21 Please code using Java and please show an example that it will run sucessf

ID: 3674666 • Letter: 2

Question

20.21

Please code using Java and please show an example that it will run sucessfully in an JAVA IDE. Code the following,

(Use Comparator) Write the following generic method using selection sort and a comparator.

public static <E> void selectionSort(E[ ] list, Comparator<? super E> comparator)

Write a test program that creates an array of 10 GeometricObjects and invokes this method using the GeometricObjectComparator introduced inListing 20.4 to sort the elements. Display the sorted elements. Use the following statement to create the array.

GeometricObject[] list = {new Circle(5), new Rectangle(4, 5),

new Circle(5.5), new Rectangle(2.4, 5), new Circle(0.5),

new Rectangle(4, 65), new Circle(4.5), new Rectangle(4.4, 1),

new Circle(6.5), new Rectangle(4, 5)};

LISTING 20.4 GeometricObjectComparator.java

import java.util.Comparator;

public class GeometricObjectComparato

implements Comparator<GeometricObject>, java.io.Serializable {

public int compare(GeometricObject o1, GeometricObject o2) {

double area1 = o1.getArea();

double area2 = o2.getArea();

if (area1 < area2)

return -1;

else if (area1 == area2)

return 0;

else

return 1;

}

}

Explanation / Answer

import java.util.Comparator;

public class SelectionSortTest {
  
   public static <E> void selectionSort(E[] list, Comparator<? super E> comparator)
   {
   for(int i = 0; i < list.length - 1; ++i)
   {
       int minInd = i;
       for(int j = i + 1; j < list.length; ++j){
           if(comparator.compare(list[j], list[minInd]) == -1){
               minInd = j;
           }
       }
       if(minInd != i){
           E temp = list[minInd];
           list[minInd] = list[i];
           list[i] = temp;
       }
   }
   }
  
   public static void main(String[] args){
       GeometricObject[] list = {new Circle(5), new Rectangle(4, 5),
               new Circle(5.5), new Rectangle(2.4, 5), new Circle(0.5),
               new Rectangle(4, 65), new Circle(4.5), new Rectangle(4.4, 1),
               new Circle(6.5), new Rectangle(4, 5)};
       selectionSort(list, new GeometricObjectComparator());
       for(int i = 0; i < list.length; ++i){
           System.out.println(list[i].toString());
       }
   }
  
}