given the obove code make the sort and the 2 classes to get output import java.
ID: 3844912 • Letter: G
Question
given the obove code make the sort and the 2 classes
to get output
import java. util Comparator public class Driver static void sort (string CJ array, Comparator c) f t for (int i 0; i array. length-1; i++ int minIndex i; complete the code for selection sort static void print Array string array t for (int i 0; i array. length; i++) System. out. print array Lil System. out. println(); public static void main string CJ args) string CJ array i''ff", "abe", "de", "fe", "z", "abc", "aaab" "aaaa", "c"1; print Array array); sort array, new LexicalComparator O); print Array array); sort array, new LengthComparator C)); print Array Carray) ;I OUTPUT ff abe de fe z abc aaab aaaa c aaaa aaab abc abe c de fe ff z c z de fe ff abc abe aaaa aaabExplanation / Answer
Below is your code: -
Driver.java
import java.util.Comparator;
public class Driver {
static void sort(String[] array,Comparator<String> c) {
for (int i = 0; i < array.length-1; i++) {
int minIndex = i;
for(int j = i+1;j < array.length;j++) {
if(c.compare(array[j], array[minIndex]) < 0) {
minIndex = j;
}
}
String smallerString = array[minIndex];
array[minIndex] = array[i];
array[i] = smallerString;
}
}
static void printArray(String[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]+" ");
}
System.out.println();
}
public static void main(String[] args) {
String[] array = {"ff","abe","de","fe","z","abc","aaab","aaaa","c"};
printArray(array);
sort(array,new LexicalComparator());
printArray(array);
sort(array,new LengthComparator());
printArray(array);
}
}
LexicalComparator.java
import java.util.Comparator;
public class LexicalComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
LengthComparator.java
import java.util.Comparator;
public class LengthComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
int len1 = o1.length();
int len2 = o2.length();
if(len1 < len2) {
return -1;
} else if(len1 > len2) {
return 1;
} else {
return 0;
}
}
}
Sample Run: -
ff abe de fe z abc aaab aaaa c
aaaa aaab abc abe c de fe ff z
c z de fe ff abc abe aaaa aaab
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.