Question: JAVA PROGRAMMING Create a comparator class instead of using the Java libraries to compare string for the program below.... import java.util.*; public class Sort_Names {
JAVA PROGRAMMING
Create a comparator class instead of using the Java libraries to compare string for the program below....
import java.util.*;
public class Sort_Names
{
public static void main(String[] args)
{
//Creating an array list
ArrayList names = new ArrayList<>();
String name;
Scanner scan = new Scanner(System.in);
for(int i = 1; i<=10; i++) {
System.out.print("Enter name "+i+" : ");
name = scan.nextLine();
names.add(name);
}
Sorting testing = new Sorting();
//Call Sort method to put names in alphabetical order and print
testing.sort(names);
System.out.println(names);
//Call reverseSort method to put names in reverse alphabetical order and print
testing.reverseSort(names);
System.out.println(names);
}
}
---------------------------------------------------------
import java.util.*;
public class Sorting {
void sort(ArrayList l) {
String temp;
int min;
for(int i = 0; i < l.size(); i++) {
min = i;
for(int j = i; j < l.size(); ++j) {
if(l.get(j).compareTo(l.get(min)) < 0) {
min = j;
}
}
temp = l.get(min);
l.set(min, l.get(i));
l.set(i, temp);
}
}
void reverseSort(ArrayList l) {
String temp;
int max;
for(int i = 0; i < l.size(); i++) {
max = i;
for(int j = i; j < l.size(); ++j) {
if(l.get(j).compareTo(l.get(max)) > 0) {
max = j;
}
}
temp = l.get(max);
l.set(max, l.get(i));
l.set(i, temp);
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
