23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Visualiz<strong>in</strong>g Game Entry Insertion<br />

To visualize this <strong>in</strong>sertion process, imag<strong>in</strong>e that we store <strong>in</strong> array entries<br />

remote controls represent<strong>in</strong>g references to the nonnull GameEntry objects,<br />

listed left-to-right from the one with highest score to the one with the lowest.<br />

Given the new game entry, e, we need to figure out where it belongs. We start this<br />

search at the end of the entries array. If the last reference <strong>in</strong> this array is not<br />

null <strong>and</strong> its score is bigger than e's score, then we can stop immediately. For, <strong>in</strong><br />

this case, e is not a high score—it doesn't belong <strong>in</strong> the entries array at all.<br />

Otherwise, we know that e belongs <strong>in</strong> the array, <strong>and</strong> we also know that the last<br />

th<strong>in</strong>g <strong>in</strong> the entries array no longer belongs there. Next, we go to the second to<br />

the last reference <strong>in</strong> the array. If this reference is null or it po<strong>in</strong>ts to a<br />

GameEntry object whose score is less thane's, this reference needs to be moved<br />

one cell to the right <strong>in</strong> the entries array. Moreover, if we move this reference,<br />

then we need to repeat this comparison with the next one, provided we haven't<br />

reached the beg<strong>in</strong>n<strong>in</strong>g of the entries array. We cont<strong>in</strong>ue compar<strong>in</strong>g <strong>and</strong><br />

shift<strong>in</strong>g references to game entries until we either reach the beg<strong>in</strong>n<strong>in</strong>g of the<br />

entries array or we compare e's score with a game entry with a higher score. In<br />

either case, we will have identified the place where e belongs. (See Figure 3.2.)<br />

Figure 3.2: Prepar<strong>in</strong>g to add a new GameEntry<br />

object to the entries array. In order to make room<br />

for the new reference, we have to shift the references<br />

to game entries with smaller scores than the new one<br />

to the right by one cell.<br />

144

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!