Create a generic bubble sort method. Refer to the pseudo code below for a description of the sorting algorithm. Your method must be able to sort an array of any type of objects that implements the Comparable interface. Create a main method that creates an array of 100 integers. The integers are to be randomly selected, ranging from 0 to 999, inclusive. Also, create an array of 100 doubles. The doubles are to be randomly generated and ranging from 0 to 100. Display the contents of both arrays before sorting and after sorting in ascending order.

for (int k=1;k for (int i=0; i if(list[i] >list[i+1])
swap list[i] with list[i+1];
}
}

Respuesta :

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:

ACCESS MORE