39_split_Introduction to Algorithms 2nd Edition

# 39_split_Introduction to Algorithms 2nd Edition - 16...

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 16 Chapter 2 Getting Started 2 ♣ ♣♣ ♣ ♣♣ 10 4 5♣ ♣ ♣ ♣♣♣ ♣ ♣ ♣ ♣ ♣♣ ♣ 7 ♣ 7 ♣ 1 0 ♣♣ ♣ 5 ♣ ♣ ♣2 ♣ ♣4 ♣ ♣ ♣ ♣♣♣ ♣♣ Figure 2.1 Sorting a hand of cards using insertion sort. employ whatever expressive method is most clear and concise to specify a given algorithm. Sometimes, the clearest method is English, so do not be surprised if you come across an English phrase or sentence embedded within a section of “real” code. Another difference between pseudocode and real code is that pseudocode is not typically concerned with issues of software engineering. Issues of data abstraction, modularity, and error handling are often ignored in order to convey the essence of the algorithm more concisely. We start with insertion sort, which is an efﬁcient algorithm for sorting a small number of elements. Insertion sort works the way many people sort a hand of playing cards. We start with an empty left hand and the cards face down on the table. We then remove one card at a time from the table and insert it into the correct position in the left hand. To ﬁnd the correct position for a card, we compare it with each of the cards already in the hand, from right to left, as illustrated in Figure 2.1. At all times, the cards held in the left hand are sorted, and these cards were originally the top cards of the pile on the table. Our pseudocode for insertion sort is presented as a procedure called I NSERTION S ORT, which takes as a parameter an array A[1 . . n ] containing a sequence of length n that is to be sorted. (In the code, the number n of elements in A is denoted by length[ A].) The input numbers are sorted in place: the numbers are rearranged within the array A, with at most a constant number of them stored outside the array at any time. The input array A contains the sorted output sequence when I NSERTION -S ORT is ﬁnished. ...
View Full Document

## This document was uploaded on 11/22/2010.

Ask a homework question - tutors are online