Java Reference
In-Depth Information
To test whether selectionSort works properly, we write Program P1.1. Only main is shown. To complete the
program, just add selectionSort , getSmallest , and swap .
Program P1.1
import java.util.*;
public class SelectSortTest {
final static int MaxNumbers = 10;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] num = new int[MaxNumbers];
System.out.printf("Type up to %d numbers followed by 0\n", MaxNumbers);
int n = 0;
int v = in.nextInt();
while (v != 0 && n < MaxNumbers) {
num[n++] = v;
v = in.nextInt();
}
if (v != 0) {
System.out.printf("\nMore than %d numbers entered\n", MaxNumbers);
System.out.printf("First %d used\n", MaxNumbers);
}
if (n == 0) {
System.out.printf("\nNo numbers supplied\n");
System.exit(1);
}
//n numbers are stored from num[0] to num[n-1]
selectionSort(num, 0, n-1);
System.out.printf("\nThe sorted numbers are\n");
for (v = 0; v < n; v++) System.out.printf("%d ", num[v]);
System.out.printf("\n");
} //end main
// selectionSort, getSmallest and swap go here
} //end class SelectSortTest
The program requests up to 10 numbers (as defined by MaxNumbers ), stores them in the array num , calls
selectionSort , and then prints the sorted list.
The following is a sample run of the program:
Type up to 10 numbers followed by 0
57 48 79 65 15 33 52 0
The sorted numbers are
15 33 48 52 57 65 79
Note that if the user enters more than ten numbers, the program will recognize this and sort only the first ten.
Search WWH ::




Custom Search