Java Reference
In-Depth Information
To use the selection sort routine, we first create an array of integers, call the
static sort function, and then display the sorted array:
public
static void main( String [ ]
args )
{ int []
array = { 22 ,35 ,19 ,26 ,20 ,13 ,42 ,37 ,11 ,24 } ;
SelectionSort(array) ;
for ( int i=0;i < array . length ; i++)
System . out . print ( array [ i ]+ "" );
System . out . println ( "" );
}
We get the sorted array:
11 13 19 20 22 24 26 35 37 42
A more verbose output will display the status of the array at all stages:
Stage 1:11 35 22 26 20 19 42 37 13 24
Stage 2:11 13 35 26 22 20 42 37 19 24
Stage 3:11 13 19 35 26 22 42 37 20 24
Stage 4:11 13 19 20 35 26 42 37 22 24
Stage 5:11 13 19 20 22 35 42 37 26 24
Stage 6:11 13 19 20 22 24 42 37 35 26
Stage 7:11 13 19 20 22 24 26 42 37 35
Stage 8:11 13 19 20 22 24 26 35 42 37
Stage 9:11 13 19 20 22 24 26 35 37 42
Note that the sorting is performed in-place : That is, we do not need extra
memory to sort the input array. Furthermore, the minimum elements are
searched iteratively in sub-arrays: At stage i + 1, every time a new minimum
is found, it is swapped with the head array[i] of the sub-array.
6.4.2 Extending selection sort to objects
Our implementation of the selection sort program works only for integer arrays.
To extend it to arbitrary object types 2 , we need to adjust the two basic
primitives: predicate GreaterThan and swapping procedure swap to the type
of considered object type. To illustrate how these changes may be performed,
consider the following type EventObject for handling objects denoting events:
class EventObject
{
int year, month, day;
EventObject(int y, int m, int d)
2 In fact, Java provides a framework called the generics for this purpose that is
beyond the scope of this topic.
 
 
Search WWH ::




Custom Search