Answer:
import java.util.Arrays;
import java.util.Random;
public class GenericSort{
/**
* Method for swapping the value
* @param list
* @param i
* @param j
*/
private static <T> void swap(T[] list, int i, int j) {
if (i != j) {
T temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
/**
* Generic method for sorting array
* who implement the comparable interface
* @param list
*/
public static <T extends Comparable<T>> void bubble_sort_(T[] list) {
//used the given algo
for (int k=1;k<list.length; k++){
for (int i=0; i<list.length-k;i++){
//using the compareTo method from comparable interface
if(list[i].compareTo(list[k])>0) {
swap(list,k,i);
}
}
}
}
public static void main(String[] args) {
Random rand = new Random();
//Array for int and double
Integer intArray[ ] = new Integer[100];
Double doubleArray []= new Double[100];
for(int i = 0;i<100;i++) {
intArray[i] = rand.nextInt(1000);
doubleArray[i] = 0 + (1000 - 0) * rand.nextDouble();
}
System.out.println("Integer Array Before Sorting ...");
System.out.println(Arrays.toString(intArray));
bubble_sort_(intArray);
System.out.println("Integer Array After sorting.....");
System.out.println(Arrays.toString(intArray));
System.out.println("\n\nDouble array Before Sorting ....");
System.out.println(Arrays.toString(doubleArray));
bubble_sort_(doubleArray);
System.out.println("Double array after sorting ...");
System.out.println(Arrays.toString(doubleArray));
}
}
Explanation: