Java Reference
In-Depth Information
//Step b
temp = list[smallestIndex];
list[smallestIndex] = list[index];
list[index] = temp;
}
}
Note that if the list contains duplicates, then while searching for the smallest element, the
method selectionSort finds the position of the first occurrence of the smallest element,
and in the successive iterations finds the positions of other occurrences of this smallest
element. Example 14-1 shows how to use the selection sort algorithm in a program.
EXAMPLE 14-1 (SELECTION SORT)
// This program illustrates how to use a selection sort algorithm
// in a program.
public class TestSelectionSort
//Line 1
{
//Line 2
public static void main(String[] args)
//Line 3
{
int list[] = {2, 56, 34, 25, 73, 46, 89,
10, 5, 16};
//Line 4
selectionSort(list, list.length);
//Line 5
System.out.println("After sorting, the "
+ "list elements are:");
//Line 6
for ( int i = 0; i < list.length; i++)
//Line 7
System.out.print(list[i] + " ");
//Line 8
System.out.println();
//Line 9
}
//Line 10
//Place the definition of the selection sort algorithm
//given previously here.
}
Sample Run:
After sorting, the list elements are:
2 5 10 16 25 34 46 56 73 89
The statement in Line 4 creates and initializes list to be an array of 10 elements of type
int . The statement in Line 5 uses the method selectionSort to sort list . Notice that
both list and its length are passed as parameters to the method selectionSort . The
for loop in Lines 7 and 8 outputs the elements of list .
In this program, to illustrate the selection sort algorithm, we declared and initialized the
array list . However, you can also prompt the user to input the data during program
execution.
 
Search WWH ::




Custom Search