Generic Insertion Sort: Modify the sorting method so it is a generic method. The
ID: 3759017 • Letter: G
Question
Generic Insertion Sort: Modify the sorting method so it is a generic method. The method should use generic notation to accept an array of any objects that implement the Comparable interface.
public class ObjectInsertionSorter {
// TODO make this method a generic method
public static void insertionSort(Comparable[] array) {
Comparable unsortedValue; // The first unsorted value
int scan; // Used to scan the array
// The outer loop steps the index variable through
// each subscript in the array, starting at 1. This
// is because element 0 is considered already sorted.
for (int index = 1; index < array.length; index++) {
// The first element outside the sorted subset is
// array[index]. Store a reference to this element
// in unsortedValue.
unsortedValue = array[index];
// Start scan at the subscript of the first element
// outside the sorted subset.
scan = index;
// Move the first element outside the sorted subset
// into its proper position within the sorted subset.
while (scan > 0 && array[scan - 1].compareTo(unsortedValue) > 0) {
array[scan] = array[scan - 1];
scan--;
}
// Insert the unsorted element in its proper position
// within the sorted subset.
array[scan] = unsortedValue;
}
}
public static void main(String[] args) {
// Create a String array with test values.
String[] values = {"Zeb", "Deb", "Will", "Karen",
"Aaron", "Chris", "Barb", "Kenny"};
// Display the array's contents.
System.out.println("Original order: ");
for (String element : values)
System.out.print(element + " ");
// Sort the array.
ObjectInsertionSorter.insertionSort(values);
// Display the array's contents.
System.out.println(" Sorted order: ");
for (String element : values)
System.out.print(element + " ");
System.out.println();
}
}
Explanation / Answer
Array sorting metod in Generic :
public class ArraySort
{
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.