Problem

Writing programs that solve the Programming Projects helps to solidify your under­standing...

Writing programs that solve the Programming Projects helps to solidify your under­standing of the material and demonstrates how the chapter’s concepts are applied. (As noted in the Introduction, qualified instructors may obtain completed solutions to the Programming Projects on the publisher’s Web site.)

In Exercise 3.2 in Chapter 3, we suggested that you could find the median of a set of data by sorting the data and picking the middle element. You might think using quicksort and picking the middle element would be the fastest way to find the median, but there’s an even faster way. It uses the partition algo­rithm to find the median without completely sorting the data.

To see how this works, imagine that you partition the data, and, by chance, the pivot happens to end up at the middle element. You’re done! All the items to the right of the pivot are larger (or equal), and all the items to the left are smaller (or equal), so if the pivot falls in the exact center of the array, then it’s the median. The pivot won’t end up in the center very often, but we can fix that by repartitioning the partition that contains the middle element.

Suppose your array has seven elements numbered from 0 to 6. The middle is element 3. If you partition this array and the pivot ends up at 4, then you need to partition again from 0 to 4 (the partition that contains 3), not 5 to 6. If the pivot ends up at 2, you need to partition from 2 to 6, not 0 to 1. You continue partitioning the appropriate partitions recursively, always checking if the pivot falls on the middle element. Eventually, it will, and you’re done. Because you need fewer partitions than in quicksort, this algorithm is faster.

Extend Programming Project 7.1 to find the median of an array. You’ll make recursive calls somewhat like those in quicksort, but they will only partition each subarray, not completely sort it. The process stops when the median is found, not when the array is sorted.

Step-by-Step Solution

Request Professional Solution

Request Solution!

We need at least 10 more requests to produce the solution.

0 / 10 have requested this problem solution

The more requests, the faster the answer.

Request! (Login Required)


All students who have requested the solution will be notified once they are available.
Add your Solution
Textbook Solutions and Answers Search
Solutions For Problems in Chapter 7
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT