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

else if (A[i] < B[j]) C[++k] = A[i++];

else C[++k] = B[j++];

}

return m + n;

} //end merge

The while loop expresses the following logic: as long as there is at least one element to process in

either A or B, we enter the loop. If we are finished with A (i == m), copy an element from B to C. If

we are finished with B (j == n), copy an element from A to C. Otherwise, copy the smaller of A[i]

and B[j] to C. Each time we copy an element from an array, we add 1 to the subscript for that array.

While the previous version implements the merge in a straightforward way, it seems

reasonable to say that this version is a bit neater.

EXERCISES 9

1. In the voting problem of Section 8.15, print the results in alphabetical order by

candidate name. Hint: in sorting the name array, when you move a name, make

sure and move the corresponding item in the vote array.

2. In the voting problem of Section 8.15, print the results in descending order by

candidate score.

3. Write a function to sort a double array in ascending order using selection sort. Do

the sort by finding the largest number on each pass.

4. Write a program to find out, for a class of students, the number of families with

1, 2, 3, ... up to 8 or more children. The data consists of the number of children

in each pupil’s family, terminated by 0. Print the results in decreasing order by

family-size popularity. That is, print the most popular family-size first and the least

popular family-size last.

5. A survey of 10 pop artists is made. Each person votes for an artist by specifying

the number of the artist (a value from 1 to 10). Write a program to read the names

of the artists, followed by the votes, and find out which artist is the most popular.

Choose a suitable end-of-data marker.

Print a table of the results with the most popular artist first and the least popular last.

6. The median of a set of n numbers (not necessarily distinct) is obtained by arranging

the numbers in order and taking the number in the middle. If n is odd, there is a

unique middle number. If n is even, then the average of the two middle values is the

median. Write a program to read a set of n positive integers (assume n < 100) and

print their median; n is not given but 0 indicates the end of the data.

7. The mode of a set of n numbers is the number that appears most frequently. For

example, the mode of 7 3 8 5 7 3 1 3 4 8 9 is 3.

275

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!