Click here to load reader
View
217
Download
3
Embed Size (px)
Citation preview
CS 280Data Structures
Professor John Peterson
Project
Questions?• http://wiki.western.edu/mcis/
index.php/CIS280/f07/project5
Quicksort Recap
• What is the algorithmic paradigm behind Quicksort?
• How do we split up the array when doing quicksort?
• What does partitioning do?• How is quicksort recursive?• How does this recursion relate to
iteration?• What is “Priming the Pump”?
Quicksort Recap
• How do we represent array segments?
• When do we stop the recursion?• How do we know the recursion won’t
go on forever?• How do we partition the array around
the pivot?• What is the special property of the
pivot?
Let’s Code on the Board
We need three methods:• quicksort• qs• partitionWhat are their signatures?
Quicksort
void quicksort(Sortable s) {
qs(s, 0, s.size()-1);}
void qs(Sortable s, int low, int high) {
if (high – low > 0) {
int p = partition(s, low, high);
qs(s, low, p-1); // sort low side
qs(s, p+1, high); // sort high side
}}
Partitioning
There are lots of ways to do partitioning – we’ll choose one of the more efficient ones.
We’ll arbitrarily select the last element in the range to be the pivot. How could we choose something different?
We’ll use two pointers (array indices) to indicate the lower and upper bound of the unpartitioned area.
Initially, lo = low and hi = high – 1
Example
{ 3, 1, 8, 4, 9, 7, 5, 2, 6 }
lo hiStrategy: slide lo up and hi down until
something out of place appears.If they haven’t crossed, swap the
elements at lo and hi, push them one closer to the middle, and repeat.
Example
{ 3, 1, 8, 4, 9, 7, 5, 2, 6 }
lo hiAfter sliding (note hi doesn’t move)Then swap:{ 3, 1, 2, 4, 9, 7, 5, 8, 6 }
lo hi
Example
{ 3, 1, 2, 4, 9, 7, 5, 8, 6 }
lo hi
Example
{ 3, 1, 2, 4, 9, 7, 5, 8, 6 }
lo hiThen swap:{ 3, 1, 2, 4, 5, 7, 9, 8, 6 }
lo hi
Final Slide
{ 3, 1, 2, 4, 5, 7, 9, 8, 6 }
hi loNo swap if they cross!Final pivot swap:{ 3, 1, 2, 4, 5, 6, 9, 8, 7 }
As Code …
int partition(Sortable s, int low, int high) {
int lo = low;
int hi = high – 1;
while (lo <= hi) {
while (lo < high && s.gtr(high, lo)) lo++;
while (hi >= low && !s.gtr(high, hi)) hi--;
if (lo <= hi) { // in case they crossed …
s.swap(lo, hi);
lo++;hi--;}}
s.swap(lo, high);
return lo; }