Question: Java, different than others Problem 4: SelectionSorter (20 pts) You are given an implementation of the selection sort algorithm that works on String arrays: SelectionSorter.java

Java, different than others

Problem 4: SelectionSorter (20 pts)

You are given an implementation of the selection sort algorithm that works on String arrays: SelectionSorter.java Download SelectionSorter.java. Modify it so that it works generically, on arrays of any type that implements the Comparable interface.

Examples:

String[] words = { "Mary", "had", "a", "little", "lamb" }; SelectionSorter strSorter = new SelectionSorter(words); strSorter.sort(); System.out.println(Arrays.toString(words)); // prints "[Mary, a, had, lamb, little]" Integer[] ints = { 13, 18, 2, 9823, 998, 187, -298, 30, 0, -98, 1, 30, 18 }; SelectionSorter intSorter = new SelectionSorter(ints); intSorter.sort(); System.out.println(Arrays.toString(ints)); // prints "[-298, -98, 0, 1, 2, 13, 18, 18, 30, 30, 187, 998, 9823]" Double[] doubles = { 46.2, -88.032, 0.01, 0.02, 1.0, 18.0, -18.0, -46.2, 0.02, -18.0, 23.697}; SelectionSorter doubleSorter = new SelectionSorter(doubles); doubleSorter.sort(); System.out.println(Arrays.toString(doubles)); // prints "[-88.032, -46.2, -18.0, -18.0, 0.01, 0.02, 0.02, 1.0, 18.0, 23.697, 46.2]" SelectionSorter.java

package labs.lab8; /** * A class for executing selection sorting on an array. */ public class SelectionSorter { private String[] a; /** * Constructs a SelectionSorter. * * @param anArray a sorted array */ public SelectionSorter(String[] anArray) { a = anArray; } /** * Sorts the array using a selection sort algorithm. * * @return The sorted list. */ public void sort() { int position; int minimum; for (position = 0; position < a.length; position++) { minimum = position; for (int i = position + 1; i < a.length; i++) { if (a[i].compareTo(a[minimum]) < 0) { minimum = i; } } if (minimum != position) { String swap = a[position]; a[position] = a[minimum]; a[minimum] = swap; } } } }

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!