15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

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

398<br />

Using Shell Sort<br />

32 9 74 21<br />

Unsorted list<br />

32<br />

9<br />

74 21<br />

Each low value is yanked out of the list . . .<br />

9 32 74 21<br />

. . . and inserted in its proper, sorted location at the<br />

beginning of the list.<br />

Figure 1-4:<br />

Insertion<br />

sort only<br />

examines a<br />

list once to<br />

sort it.<br />

21<br />

9 32 74<br />

9 21 32 74<br />

Final sorted list<br />

One major advantage of the insertion sort algorithm is that it only needs to<br />

examine an entire list once to sort it. In comparison, bubble sort must repetitively<br />

examine the entire list multiple times, and selection sort must repetitively<br />

examine progressively smaller lists multiple times. As a result, the<br />

insertion sort algorithm is much faster while being easy to implement as<br />

well.<br />

Using Shell Sort<br />

To speed up the per<strong>for</strong>mance of the insertion sort algorithm, Donald Shell, a<br />

computer scientist, created a variation of the insertion sort algorithm<br />

dubbed shell sort.<br />

One problem with insertion sort is that it must examine one value at a time.<br />

In a long list, this can take a long time. Shell sort works by dividing a long list<br />

into several smaller ones and then per<strong>for</strong>ming an insertion sort on each<br />

smaller list. After each smaller list gets sorted, the shell sort algorithm uses<br />

an ordinary insertion sort to sort the entire list one last time. By this time,<br />

the longer list is nearly sorted so this final insertion sort occurs quickly, as<br />

shown in Figure 1-5.<br />

Basically, shell sort works like this:<br />

1. Divide a long list into multiple smaller lists.<br />

2. Arrange each list in a grid or table consisting of rows and columns.

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

Saved successfully!

Ooh no, something went wrong!