20.02.2021 Aufrufe

[Thomas_H._Cormen]_Algorithms_unlocked(BookZZ.org)

Erfolgreiche ePaper selbst erstellen

Machen Sie aus Ihren PDF Publikationen ein blätterbares Flipbook mit unserer einzigartigen Google optimierten e-Paper Software.

Chapter 3: Algorithms for Sorting and Searching 33

whose name comes first alphabetically. Now go through the bookshelf,

left to right, starting with the book in slot 2 to find the book in slots 2

through n whose author name comes earliest in the alphabet. Suppose

that it’s by Jane Austen. Swap the location of this book with the book

in slot 2, so that now slots 1 and 2 have the first and second books in the

overall alphabetical ordering. Then do the same for slot 3, and so on.

Once we have put the correct book into slot n 1 (perhaps it’s by H. G.

Wells), we are done, because there’s only one book left (say, a book by

Oscar Wilde), and it’s in slot n where it belongs.

To turn this approach into a computer algorithm, change the bookshelf

to an array and the books to array elements. Here’s the result:

Procedure SELECTION-SORT.A; n/

Inputs:

A: an array.

n: the number of elements in A to sort.

Result: The elements of A are sorted into nondecreasing order.

1. For i D 1 to n 1:

A. Set smallest to the index of the smallest element in the

subarray AŒi : : n.

B. Swap AŒi with AŒsmallest.

Finding the smallest element in AŒi : : n is a variant on linear search.

First declare AŒi to be the smallest element seen in the subarray so far,

and then go through the rest of the subarray, updating the index of the

smallest element every time we find an element less than the current

smallest. Here’s the refined procedure:

Procedure SELECTION-SORT.A; n/

Inputs and Result: Same as before.

1. For i D 1 to n 1:

A. Set smallest to i.

B. For j D i C 1 to n:

i. If AŒj < AŒsmallest, then set smallest to j .

C. Swap AŒi with AŒsmallest.

Hurra! Ihre Datei wurde hochgeladen und ist bereit für die Veröffentlichung.

Erfolgreich gespeichert!

Leider ist etwas schief gelaufen!