Page 462 - Introduction to Programming with Java: A Problem Solving Approach
P. 462
428
Chapter 10 Arrays and ArrayLists
11.
Write a public method named equals for your Students class that tests whether two Students objects are equal. Your equals method should be written such that the above main method would produce this output:
s1 == s3
Only provide code for the asked-for equals method; do not provide code for the entire Students class.
[after §10.8] Given the following list array, use the Selection Sort algorithm to sort the array. Show each step of the selection sort process. Do not provide code; just show pictures of the list array after each element swap.
list list
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Apago PDF Enhancer
}
// end insertionSort
}
// end for
}
(original)
00 11 22 33 44
(sorted)
12
2
4
0
9
4
0
2
9
12
12.
[after §10.8] The Insertion Sort algorithm provides an alternative to the Selection Sort algorithm for sorting small numbers of items (of order 20 or less). It’s not quite as efficient as Selection Sort for arrays, but it is slightly more efficient for other kinds of data collections. The following code implements the Insertion Sort algorithm:
public static void insertionSort(int[] list)
{
int temp;
int j;
for (int i=1; i<list.length; i++)
{
temp = list[i];
for (j=i; j>0 && temp<list[j-1]; j--)
{
list[j] = list[j-1];
list[j] = temp;
Note that the scope of the j count variable extends beyond the scope of the for loop in which it’s used. Assume that an array of int has been instantiated and the insertionSort method has been called with a reference to this array passed in as a parameter. Trace the execution of this method, using the following header and initial entries:
Sort
<arrays>
line#
insertionSort
arr1
(list)
i
j
temp
length
0
1
2
3
4
3333
1234
2222
1000
10
arr1