87.2k views
5 votes
--IN JAVA--Write the following two generic methods using bubble sort. The first method sorts the elements using the Comparable interface, and the second uses the Comparator interface.

public static >
void bubbleSort(E[] list)
public static void bubbleSort(E[] list,
Comparator<? super E> comparator)
Write the entire program to test the bubbleSort using 10 elements in an array. You will decide the data type and enter the elements for testing purposes.

User MicroMan
by
8.7k points

1 Answer

0 votes

Final answer:

The detailed answer includes Java code for two generic bubble sort methods, one using Comparable and the other using Comparator, along with a main method to test these sorting methods with an array of 10 integers.

Step-by-step explanation:

The question pertains to writing two generic methods in Java for sorting an array using bubble sort - one using the Comparable interface, and the other using a Comparator. Here is the Java code that accomplishes this, along with a program to test the sorting with an array of 10 integers:

import java.util.Comparator;
public class BubbleSortTest {
public static > void bubbleSort(E[] list) {
E temp;
boolean swapped;
for (int i = 0; i < list.length - 1; i++) {
swapped = false;
for (int j = 0; j < list.length - 1 - i; j++) {
if (list[j].compareTo(list[j + 1]) > 0) {
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
swapped = true;
}
}
if (!swapped) break;
}
}
public static void bubbleSort(E[] list, Comparator comparator) {
E temp;
boolean swapped;
for (int i = 0; i < list.length - 1; i++) {
swapped = false;
for (int j = 0; j < list.length - 1 - i; j++) {
if (comparator.compare(list[j], list[j + 1]) > 0) {
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
swapped = true;
}
}
if (!swapped) break;
}
}
public static void main(String[] args) {
Integer[] numbers = {35, 23, 48, 12, 56, 44, 2, 49, 19, 37};
bubbleSort(numbers);
for (int number : numbers) {
System.out.print(number + " ");
}
System.out.println();
bubbleSort(numbers, Comparator.naturalOrder());
for (int number : numbers) {
System.out.print(number + " ");
}
}
}

This example uses an array of integers which is a common data type for demonstrating sorting algorithms. You can replace Integer with any other Comparable objects to test the generic methods.

User Mnikley
by
7.9k points