5 * $Id: InsertSort.java,v 1.3 2000/11/28 13:33:25 cs2 Exp $
8 * $Log: InsertSort.java,v $
9 * Revision 1.3 2000/11/28 13:33:25 cs2
10 * Defined symbolic constants for the number of
11 * numbers to sort (ARRAY_SIZE) and for the maximum
12 * random number that will be generated (MAX_NUMBER)
14 * Revision 1.2 2000/11/28 13:31:36 cs2
15 * Added import statement for Random class
17 * Revision 1.1 2000/11/28 13:31:10 cs2
22 import java
.util
.Random
;
25 * Sort an array using an insertion sort.
28 public class InsertSort
{
33 * @param args[] the command line arguments
36 public static void main( String args
[] ) {
37 final int ARRAY_SIZE
= 10;
38 final int MAX_NUMBER
= 100;
40 int data
[] = new int[ ARRAY_SIZE
];
42 Random randomNumbers
= new Random();
44 // Sort ARRAY_SIZE random numbers between 0 and MAX_NUMBER
46 for ( int i
= 0; i
< data
.length
; i
++ ) {
48 // Add the newest number to the end of the array
50 data
[ i
] = randomNumbers
.nextInt( MAX_NUMBER
);
52 // Starting at the bottom of the array, move the last number
53 // up until it is in the correct position.
55 for ( int j
= i
- 1; j
>= 0 && data
[ j
+ 1 ] < data
[ j
]; j
-- ) {
57 data
[ j
] = data
[ j
+ 1];
62 // Print out the sorted array
64 for ( int i
= 0; i
< data
.length
; i
++ )
65 System
.out
.println( data
[ i
] );