Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 280 Data Structures Professor John Peterson. Project Questions? /CIS280/f07/project5http://wiki.western.edu/mcis/index.php.

Similar presentations


Presentation on theme: "CS 280 Data Structures Professor John Peterson. Project Questions? /CIS280/f07/project5http://wiki.western.edu/mcis/index.php."— Presentation transcript:

1 CS 280 Data Structures Professor John Peterson

2 Project Questions? http://wiki.western.edu/mcis/index.php /CIS280/f07/project5http://wiki.western.edu/mcis/index.php /CIS280/f07/project5

3 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”?

4 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?

5 Let’s Code on the Board We need three methods: quicksort qs partition What are their signatures?

6 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 }}

7 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

8 Example { 3, 1, 8, 4, 9, 7, 5, 2, 6 } lo hi Strategy: 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.

9 Example { 3, 1, 8, 4, 9, 7, 5, 2, 6 } lo hi After sliding (note hi doesn’t move) Then swap: { 3, 1, 2, 4, 9, 7, 5, 8, 6 } lo hi

10 Example { 3, 1, 2, 4, 9, 7, 5, 8, 6 } lo hi

11 Example { 3, 1, 2, 4, 9, 7, 5, 8, 6 } lo hi Then swap: { 3, 1, 2, 4, 5, 7, 9, 8, 6 } lo hi

12 Final Slide { 3, 1, 2, 4, 5, 7, 9, 8, 6 } hi lo No swap if they cross! Final pivot swap: { 3, 1, 2, 4, 5, 6, 9, 8, 7 }

13 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; }


Download ppt "CS 280 Data Structures Professor John Peterson. Project Questions? /CIS280/f07/project5http://wiki.western.edu/mcis/index.php."

Similar presentations


Ads by Google