Question: Help with Selection Sort Algorithm with custom Comparator. I have an assignment to implement a selection sort algorithm and pass an order defined by the

Help with Selection Sort Algorithm with custom Comparator.

I have an assignment to implement a selection sort algorithm and pass an order defined by the comparator and have it print the list. The custom order is to sort the List of names ordered in descending order of the first name followed by the last name. Code Below:

import java.util.Collections; import java.util.Comparator; import java.util.List; public class NameSortUtil { /**  * Sorts the specified list into ascending order, according to the natural  * ordering of its elements.  *  * @param list - the list to be sorted.  */  public static List selectionSort(List list) { //goings through every element of the list for(int i = 0; i < list.size(); i++) { //keeps current position int pos = i; //goes through the rest of the list after for(int j = i; j < list.size(); j++) { //Checks to make sure it is in the right location if(list.get(j).compareTo(list.get(i)) < 0) { pos = j; } } //Swap min name to current position Name minName = list.get(pos); list.set(pos, list.get(i)); list.set(i, minName); } return list; } /**  * Sorts the specified list according to the order induced by the specified  * comparator.  * @param list - the list to be sorted.  */  public static List selectionSort2(List list) { list.sort(new Comparator() { public int compare(Name one, Name other) { return one.getLastName().compareTo(other.getLastName()); } }); return list; // TODO: implement the selection sort algorithm to sort a  // list of Name objects into the order defined by the // comparator. } }

import com.sun.jdi.VoidType; import javax.swing.*; import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class NameSortTester { public static void main(String args[]) throws FileNotFoundException { JFileChooser chooser = new JFileChooser(); //JFileChooser object. chooser.setDialogTitle("Open File...: "); //Prompts the dialog. int result = chooser.showOpenDialog(null); //Shows up the open dialog. if (result == JFileChooser.APPROVE_OPTION) { //Check if the user selects a file or not. //Picks up the selected file File file = chooser.getSelectedFile(); List list = NameDataLoader.load(file); List list1 = NameSortUtil.selectionSort(list); List list2 = NameSortUtil.selectionSort2(list); System.out.println(list1.toString()); System.out.println(list2.toString()); } } } 

And if you're wondering, the Name class has my setters, getters, and a compareTo method that's overridden.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!