Java Reference
In-Depth Information
38
39
System.out.printf( "%d* " , data[index]); // indicate swap
40
41
// finish outputting array
42
for ( int i = index + 1 ; i < data.length; i++)
43
System.out.printf( "%d " , data[i]);
44
45
System.out.printf( "%n " ); // for alignment
46
47
// indicate amount of array that's sorted
48
for ( int i = 0 ; i <= pass; i++)
49
System.out.print( "-- " );
50
System.out.println();
51
}
52
53
public static void main(String[] args)
54
{
55
SecureRandom generator = new SecureRandom();
56
57
int [] data = new int [ 10 ]; // create array
58
59
for ( int i = 0 ; i < data.length; i++) // populate array
60
data[i] = 10 + generator.nextInt( 90 );
61
62
System.out.printf( "Unsorted array:%n%s%n%n",
63
Arrays.toString(data)); // display array
64
insertionSort(data); // sort array
65
66
System.out.printf( "Sorted array:%n%s%n%n",
67
Arrays.toString(data)); // display array
68
}
69
} // end class InsertionSortTest
Unsorted array:
[34, 96, 12, 87, 40, 80, 16, 50, 30, 45]
after pass 1: 34 96* 12 87 40 80 16 50 30 45
-- --
after pass 2: 12* 34 96 87 40 80 16 50 30 45
-- -- --
after pass 3: 12 34 87* 96 40 80 16 50 30 45
-- -- -- --
after pass 4: 12 34 40* 87 96 80 16 50 30 45
-- -- -- -- --
after pass 5: 12 34 40 80* 87 96 16 50 30 45
-- -- -- -- -- --
after pass 6: 12 16* 34 40 80 87 96 50 30 45
-- -- -- -- -- -- --
after pass 7: 12 16 34 40 50* 80 87 96 30 45
-- -- -- -- -- -- -- --
after pass 8: 12 16 30* 34 40 50 80 87 96 45
-- -- -- -- -- -- -- -- --
Fig. 19.5 | Sorting an array with insertion sort. (Part 2 of 3.)
Search WWH ::




Custom Search