Question: This is the version you will start with: /* Integer Bubble Sort */ public class IntBubbleSorter { public static void bubbleSort(int[] array) { int lastPos;

This is the version you will start with:

/* Integer Bubble Sort */

public class IntBubbleSorter

{

public static void bubbleSort(int[] array)

{

int lastPos;

int index;

int temp;

for (lastPos = array.length-1; lastPos >= 0; lastPos--)

{

for (index = 0; index <= lastPos -1; index++)

{

if (array[index] > array[index + 1])

{

temp = array[index];

array[index] = array[index+1];

array[index+1] = temp;

}

}

}

}

}

This is what youll adapt it into (i.e. convert it to using Generics):

/* The Generic Bubble Sort */

public class GenericBubbleSorter

{

public static < E extends Comparable > void bubbleSort(E[]

array)

{

int lastPos;

int index;

E temp;

for (lastPos = array.length-1; lastPos >= 0; lastPos--)

{

for (index = 0; index <= lastPos -1; index++)

{

// if (array[index] > array[index + 1])

if (array[index].compareTo(array[index + 1]) > 0)

{

temp = array[index];

array[index] = array[index+1];

array[index+1] = temp;

}

}

}

}

}

Show them the changes you make for the method to use Generics, and why (e.g. using CompareTo() istead of >).

Student Exercise

The test code for the integer Bubble Sort is given below.

Their task is to adapt it to use the Gernic version of the method above to have it sort list of three differnet types (integer, double, and string).

They will need to create their own short lists of each type.

They do not need to show the code executing.

Demonstration Exercise

public class BubbleSortTest

{

public static void main(String[] args)

{

int[] values = {5, 1, 3, 6, 4, 2};

System.out.println("Original order: ");

for (int element : values)

System.out.print(element + " ");

IntBubbleSorter.bubbleSort(values);

System.out.println(" Sorted order: ");

for (int element : values)

System.out.print(element + " ");

System.out.println();

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!