9 date 2000.11.28.13.36.59; author cs2; state Exp;
14 date 2000.11.28.13.33.25; author cs2; state Exp;
19 date 2000.11.28.13.31.36; author cs2; state Exp;
24 date 2000.11.28.13.31.10; author cs2; state Exp;
35 @Finished commenting the code and corrected minor style
43 * $Id: InsertSort.java,v 1.3 2000/11/28 13:33:25 cs2 Exp cs2 $
46 * $Log: InsertSort.java,v $
47 * Revision 1.3 2000/11/28 13:33:25 cs2
48 * Defined symbolic constants for the number of
49 * numbers to sort (ARRAY_SIZE) and for the maximum
50 * random number that will be generated (MAX_NUMBER)
52 * Revision 1.2 2000/11/28 13:31:36 cs2
53 * Added import statement for Random class
55 * Revision 1.1 2000/11/28 13:31:10 cs2
60 import java.util.Random;
63 * Sort an array using an insertion sort.
66 public class InsertSort {
69 * The main method. Fill an array with random numbers performing
70 * an insertion sort as each number is generated. After the numbers
71 * have been generated and inserted into the array, the contents of
72 * the array will be printed.
74 * @@param args[] the command line arguments (ignored)
77 public static void main( String args[] ) {
78 final int ARRAY_SIZE = 10; // Number of numbers to sort
79 final int MAX_NUMBER = 100; // Largest number to sort
81 int data[] = new int[ ARRAY_SIZE ]; // Array that will be sorted
82 int tmp = 0; // Temp storage
83 Random randomNumbers = new Random(); // Generator for random numbers
85 // Sort ARRAY_SIZE random numbers between 0 and MAX_NUMBER
87 for ( int i = 0; i < data.length; i++ ) {
89 // Add the newest number to the end of the array
91 data[ i ] = randomNumbers.nextInt( MAX_NUMBER );
93 // Starting at the bottom of the array, move the last number
94 // up until it is in the correct position.
96 for ( int j = i - 1; j >= 0 && data[ j + 1 ] < data[ j ]; j-- ) {
98 data[ j ] = data[ j + 1];
103 // Print out the sorted array
105 for ( int i = 0; i < data.length; i++ ) {
106 System.out.println( data[ i ] );
116 @Defined symbolic constants for the number of
117 numbers to sort (ARRAY_SIZE) and for the maximum
118 random number that will be generated (MAX_NUMBER)
123 * $Id: InsertSort.java,v 1.2 2000/11/28 13:31:36 cs2 Exp cs2 $
130 * @@param args[] the command line arguments
133 final int ARRAY_SIZE = 10;
134 final int MAX_NUMBER = 100;
137 int data[] = new int[ ARRAY_SIZE ];
139 Random randomNumbers = new Random();
142 for ( int i = 0; i < data.length; i++ )
149 @Added import statement for Random class
154 * $Id: InsertSort.java,v 1.1 2000/11/28 13:31:10 cs2 Exp cs2 $
158 int data[] = new int[ 10 ];
161 // Sort 10 random numbers between 0 and 100
164 data[ i ] = randomNumbers.nextInt( 100 );