08.01.2023 Views

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

Create successful ePaper yourself

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

Chapter 9 ■ Searching, Sorting, and Merging

We can use this function as follows:

n = search(name, "Carol Khan", 1, 7);

if (n > 0) printf("%s received %d vote(s)\n", name[n], vote[n]);

else printf("Name not found\n");

Using our sample data, search will return 6, which will be stored in n. Since 6 > 0, the code

will print

Carol Khan received 2 vote(s)

9.2 Selection Sort

Consider the voting program of Section 8.15. In Program P8.8, we printed the results in the order

in which the names were given. But suppose we want to print the results in alphabetical order

by name or in order by votes received, with the winner(s) first. We would have to rearrange the

names or the votes in the order we want. We say we would have to sort the names in ascending

order or sort the votes in descending order.

Sorting is the process by which a set of values are arranged in ascending or descending order.

There are many reasons to sort. Sometimes we sort in order to produce more readable output (for

example, to produce an alphabetical listing). A teacher may need to sort her students in order by

name or by average score. If we have a large set of values and we want to identify duplicates, we

can do so by sorting; the repeated values will come together in the sorted list. There are many

ways to sort. We will discuss a method known as selection sort.

Consider the following array:

Sorting num in ascending order using selection sort proceeds as follows:

1st pass

• Find the smallest number in positions 0 to 6; the smallest is 15, found in

position 4.

• Interchange the numbers in positions 0 and 4. We get this:

246

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!