We have previously studied the Selection Sort algorithm when we discussed interfaces:
public static void selectionSort(ComparableThing[] list)
{
for (int i = 0; i < list.length-1; i++)
{
/* -----------------------------------------------
Find the minimum in the list[i..list.length-1]
----------------------------------------------- */
ComparableThing min = list[i]; // Assume first element is min
int minIndex = i; // Index where min is found
for ( int k = minIndex+1; k < list.length; k++ )
if ( list[k].compareTo(min) < 0 ) // compare list[k] and min
{
min = list[k]; // Update min value
minIndex = k; // Update its index
}
/* ------------------------------------------------------
Swap list[i] with list[minIndex] if necessary
------------------------------------------------------ */
if ( minIndex != i )
exch( list, i, minIndex ); // Swap list[minIndex] and list[i]
}
}
|
Note: this selectionSort( ) is not generic --- we will write it as a generic method
The syntax to define a generic (parameterized) method is:
public static <T> void selectionSort(T[] list)
{
for (int i = 0; i < list.length-1; i++)
{
/* -----------------------------------------------
Find the minimum in the list[i..list.length-1]
----------------------------------------------- */
T min = list[i]; // Assume first element is min
int minIndex = i; // Index where min is found
for ( int k = minIndex+1; k < list.length; k++ )
if ( list[k].compareTo(min) < 0 ) // compare list[k] and min
{
min = list[k]; // Update min value
minIndex = k; // Update its index
}
/* ------------------------------------------------------
Swap list[i] with list[minIndex] if necessary
------------------------------------------------------ */
if ( minIndex != i )
exch( list, i, minIndex ); // Swap list[minIndex] and list[i]
}
}
|
However: this generic selectionSort( ) will accept arrays of non Comparable objects as parameter !!!
We can limit the type parameter T to subclasses of Comparable<T> as follows:
public static <T extends Comparable<T> > void selectionSort(T[] list)
{
for (int i = 0; i < list.length-1; i++)
{
/* -----------------------------------------------
Find the minimum in the list[i..list.length-1]
----------------------------------------------- */
T min = list[i]; // Assume first element is min
int minIndex = i; // Index where min is found
for ( int k = minIndex+1; k < list.length; k++ )
if ( list[k].compareTo(min) < 0 ) // compare list[k] and min
{
min = list[k]; // Update min value
minIndex = k; // Update its index
}
/* ------------------------------------------------------
Swap list[i] with list[minIndex] if necessary
------------------------------------------------------ */
if ( minIndex != i )
exch( list, i, minIndex ); // Swap list[minIndex] and list[i]
}
}
|
DEMO: demo/14-sort/02-sel-sort/Demo.java (Integer) + Demo2.java (String) + Demo3.java (NonComparable)
|
|
|
|
|
There are 2 additional properties of sorting algorithms that are sometimes of interest:
|