IN JAVA Write a generic insertionSort method based on the insertion sort program
ID: 3580911 • Letter: I
Question
IN JAVA
Write a generic insertionSort method based on the insertion sort program in chapter 23 of the textbook to sort Integer and Double objects. Write a test program that sorts and prints an Integer array and a Double array with your generic insertionSort method. You should also implement a generic printArray method to print the Integer and Double array. The insertion sort program is given with this assignment. Your program output should look like the sample run of the program below. A sample run of the program is as follow: Integer values in original order 9 23 63 83 11 1 7 52 Integer values in ascending order 1 2 3 5 6 7 9 11 23 83 Double values in original order 9.9 3.8 5.2 7.7 1.5 8.8 3.3 6.6 8.3 Double values in ascending order 1.5 3.3 3.8 5.2 6.6 7.7 8.3 8.8 9.9Explanation / Answer
class InsertionSort
{
public static <T extends Comparable<T>> void insertionSort (T[] list, int size)
{
int i, j;
T temp;
for (i = 1; i < size; i++)
{
temp = list[i];
for (j = i; j > 0 && list[j - 1].compareTo(temp) > 0; j--)
{
list[j] = list[j - 1];
}
list[j] = temp;
}
}
public static <T extends Comparable<T>> void printList(T[] list){
for(T i:list){
System.out.print( i + " ");
}
System.out.println();
}
}
public class InsertionSortDemo
{
public static void main (String[] args)
{
Integer list[] = {9, 23, 6, 3, 83, 11, 1, 7, 5, 2};
System.out.println("Integer values in original order");
InsertionSort.printList(list);
InsertionSort.insertionSort(list, list.length);
System.out.println("Integer values in ascending order");
InsertionSort.printList(list);
Double arr1[] = {9.9, 3.8, 5.2, 7.7, 1.5, 8.8, 3.3, 6.6, 8.3};
System.out.println("Double values in original order");
InsertionSort.printList(arr1);
InsertionSort.insertionSort(arr1, arr1.length);
System.out.println("Double values in ascending order");
InsertionSort.printList(arr1);
}
}
/*
Integer values in original order
9 23 6 3 83 11 1 7 5 2
Integer values in ascending order
1 2 3 5 6 7 9 11 23 83
Double values in original order
9.9 3.8 5.2 7.7 1.5 8.8 3.3 6.6 8.3
Double values in ascending order
1.5 3.3 3.8 5.2 6.6 7.7 8.3 8.8 9.9
*/