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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

This simple <strong>in</strong>sertion–sort algorithm goes as follows. We start with the first<br />

character <strong>in</strong> the array. One character by itself is already sorted. Then we consider<br />

the next character <strong>in</strong> the array. If it is smaller than the first, we swap them. Next<br />

we consider the third character <strong>in</strong> the array. We swap it leftward until it is <strong>in</strong> its<br />

proper order with the first two characters. We then consider the fourth character,<br />

<strong>and</strong> swap it leftward until it is <strong>in</strong> the proper order with the first three. We cont<strong>in</strong>ue<br />

<strong>in</strong> this manner with the fifth <strong>in</strong>teger, the sixth, <strong>and</strong> so on, until the whole array is<br />

sorted. Mix<strong>in</strong>g this <strong>in</strong>formal description with programm<strong>in</strong>g constructs, we can<br />

express the <strong>in</strong>sertion-sort algorithm as shown <strong>in</strong> Code Fragment 3.5.<br />

Code Fragment 3.5: High-level description of the<br />

<strong>in</strong>sertion-sort algorithm.<br />

This is a nice, high-level description of <strong>in</strong>sertion-sort. It also demonstrates why<br />

this algorithm is called "<strong>in</strong>sertion-sort"—because each iteration of the ma<strong>in</strong><br />

<strong>in</strong>serts the next element <strong>in</strong>to the sorted part of the array that comes before it.<br />

Before we can code this description up, however, we need to work out more of<br />

the details of how we do this <strong>in</strong>sertion task.<br />

Div<strong>in</strong>g <strong>in</strong>to those details a bit more, let us rewrite our description so that we now<br />

use two nested loops. The outer loop will consider each element <strong>in</strong> the array <strong>in</strong><br />

turn <strong>and</strong> the <strong>in</strong>ner loop will move that element to its proper location with the<br />

(sorted) subarray of characters that are to its left.<br />

Ref<strong>in</strong><strong>in</strong>g the Details for Insertion-Sort<br />

Ref<strong>in</strong><strong>in</strong>g the details, then, we can describe our algorithm as shown <strong>in</strong> Code<br />

Fragment 3.6.<br />

Code Fragment 3.6: Intermediate-level description<br />

of the <strong>in</strong>sertion-sort algorithm.<br />

150

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

Saved successfully!

Ooh no, something went wrong!