Question: Java Programming: Create a program called GeneralizedBubbleSort that will make use of the Comparable Interface in the same way it is used in the GeneralizedSelectionSort.
Java Programming:
Create a program called GeneralizedBubbleSort that will make use of the Comparable Interface in the same way it is used in the GeneralizedSelectionSort. You should use the attached ComparableDemo to test your program.
\\\\\\\\\\\\\\\\\\ GeneralizedSelectionSort.java \\\\\\\\\\\\\\
public class GeneralizedSelectionSort {
public static void sort(Comparable[] a, int numberUsed) { int index, indexOfNextSmallest; for (index = 0; index < numberUsed - 1; index++) { indexOfNextSmallest = indexOfSmallest(index, a, numberUsed); interchange(index,indexOfNextSmallest, a); } }
private static int indexOfSmallest(int startIndex, Comparable[] a, int numberUsed) { Comparable min = a[startIndex]; int indexOfMin = startIndex; int index; for (index = startIndex + 1; index < numberUsed; index++) if (a[index].compareTo(min) < 0) { min = a[index]; indexOfMin = index; } return indexOfMin; }
private static void interchange(int i, int j, Comparable[] a) { Comparable temp; temp = a[i]; a[i] = a[j]; a[j] = temp; } }
\\\\\\\\\\\\\\\\\\\\\\\ ComparableDemo \\\\\\\\\\\\\\\\\\\\
public class ComparableDemo { public static void main(String[] args) { Double[] d = new Double[10]; for (int i = 0; i < d.length; i++) d[i] = new Double(d.length - i);
System.out.println("Before sorting:"); int i; for (i = 0; i < d.length; i++) System.out.print(d[i].doubleValue( ) + ", "); System.out.println( );
GeneralizedSelectionSort.sort(d, d.length);
System.out.println("After sorting:"); for (i = 0; i < d.length; i++) System.out.print(d[i].doubleValue( ) + ", "); System.out.println( );
String[] a = new String[10]; a[0] = "dog"; a[1] = "cat"; a[2] = "cornish game hen"; int numberUsed = 3;
System.out.println("Before sorting:"); for (i = 0; i < numberUsed; i++) System.out.print(a[i] + ", "); System.out.println( );
GeneralizedSelectionSort.sort(a, numberUsed);
System.out.println("After sorting:"); for (i = 0; i < numberUsed; i++) System.out.print(a[i] + ", "); System.out.println( ); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
