08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

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

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

Chapter 9 ■ Searching, Sorting, and Merging

We urge you to try Exercises 1 and 2 to print the results of the voting problem in ascending

order by name and descending order by votes received.

9.2.1 Analysis of Selection Sort

To find the smallest of k items, we make k-1 comparisons. On the first pass, we make n-1

comparisons to find the smallest of n items. On the second pass, we make n-2 comparisons to

find the smallest of n-1 items. And so on, until the last pass where we make one comparison to

find the smaller of two items. In general, on the ith pass, we make n-i comparisons to find the

smallest of n-i+1 items. Hence:

Total number of comparisons = 1 + 2 + ...+ n-1 = ½ n(n-1) » ½ n 2

We say selection sort is of order O(n 2 ) (“big O n squared”). The constant ½ is not important in

“big O” notation since, as n gets very big, the constant becomes insignificant.

On each pass, we swap two items using three assignments. We make n-1 passes so we make

3(n-1) assignments in all. Using “big O” notation, we say that the number of assignments is O(n).

The constants 3 and 1 are not important as n gets large.

Does selection sort perform any better if there is order in the data? No. One way to find out

is to give it a sorted list and see what it does. If you work through the algorithm, you will see that

the method is oblivious to order in the data. It will make the same number of comparisons every

time, regardless of the data.

As an exercise, modify the programming code so that it counts the number of comparisons

and assignments made in sorting a list using selection sort.

9.3 Insertion Sort

Consider the same array as before:

Think of the numbers as cards on a table and picked up one at a time in the order in which they

appear in the array. Thus, we first pick up 57, then 48, then 79, and so on, until we pick up 52.

However, as we pick up each new number, we add it to our hand in such a way that the numbers

in our hand are all sorted.

When we pick up 57, we have just one number in our hand. We consider one number to be sorted.

When we pick up 48, we add it in front of 57 so our hand contains

48 57

When we pick up 79, we place it after 57 so our hand contains

48 57 79

252

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!