Title: Computer Science 101 A Survey of Computer Science
1Computer Science 101A Survey of Computer Science
2Divide and Conquer
3Divide and Conquer
- Divide and Conquer is a common strategy used in
computer science. - The idea is that for a given problem, we try to
break it into smaller problems (perhaps of the
same type and then solve the smaller problems) - Of course, we must consider how to solve the
smaller problems.
4Sorting -Quicksort
- Strategy - Divide and Conquer
- Partition list with small elements in first part
and large elements in second part - Sort the first part.
- Sort the second part.
5Quicksort (cont.)
- Question - How do we sort the sections?Answer -
Apply Quicksort to them. - Recursive algorithm - one which makes use of
itself to solve smaller problems of the same type.
6Quicksort (cont.)
- Question - Will this recursive process ever
stop? - Answer - Yes, when the problem is small enough
, we no longer use recursion. Such cases are
called anchor cases.
7Recursion Example
- The factorial function could be defined this
way n! 1 if n1 n ((n-1)!)
otherwise - Example 4! 4 x 3! 4 x 3 x 2! 4 x 3 x 2
x 1! 4 x 3 x 2 x 1 -
8Quicksort - Partitioning
- To partition, we choose a pivot element from
the list. - The elements which are less than or equal to the
pivot go into the first section. - The elements larger than the pivot go into the
second section.
9Quicksort - The Pivot
- Ideal would be to choose the median as the pivot,
but this would take too long. - Some programs just choose the first element.
- Our choice - choose the median of the first three
elements.
10Quicksort Partition
- Variables
- N(I),N(I1), , N(K) - list to partition
- P - position of the pivot element
- L - Right hand marker for the first section
- U - Left hand marker for the second section
11Quicksort Partition Algorithm
- Exchange the median of the first 3 elements
with the first elementSet P to first position of
listSet L to second position of listSet U to
last position of listWhile L U do While N(L)
? N(P) do Set L to L1 end-of-loop While N(U)
gt N(P) do Set U to U-1 end-of-loop If L lt U
then Exchange N(L) and N(U)end-of-loopExchange
N(P) and N(U)
12QuickSort - The Algorithm
- If the list to sort has more than 1 element
then If the list has exactly two elements then
If the elements are out of order
then Exchange them else Perform the
Partition Algorithm on list Apply QuickSort
to the first section Apply QuickSort to the
second section - Note Anchor cases are when the list has 1 or 2
elements recursion is used for 3 or more.
13Quicksort Example
14Quicksort Example (Cont.)
15Quicksort Example (Cont.)
16Quicksort Example (Cont.)
17Quicksort Example (Cont.)
18Quicksort Example (Cont.)
19Quicksort Example (Cont.)
20Quicksort Example (Cont.)
21Quicksort Example (Cont.)
22Student(?) sorts exam papers
23If your way's so good, then prove it!