Download presentation
Presentation is loading. Please wait.
1
CS 280 Data Structures Professor John Peterson
2
Test #1 We’ll do a test next week on Wednesday. It will take the entire period. You can have 1 page of notes. Think about all of the homework / projects / quizzes we’ve had. I’ll be doing something similar. There will be a little programming. I have graded homework! I’m slowly getting projects graded – watch your email.
3
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
4
Example { 3, 8, 4, 2, 5, 7, 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.
5
Example { 3, 8, 4, 2, 5, 7, 6 } lo hi After the slide, lo points to something that is too big and hi points to something that is too low (compared to pivot)
6
Example { 3, 5, 4, 2, 8, 7, 6 } lo hi After the swap
7
Example { 3, 5, 4, 2, 8, 7, 6 } lo hi Then push them one closer …
8
Example { 3, 5, 4, 2, 8, 7, 6 } hi lo And slide again … This time they have crossed so we’re done (almost). To finish, swap lo and the pivot, then return “lo”. { 3, 5, 4, 2, 6, 7, 8 }
9
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); // put pivot in middle return lo; }
10
Quicksort 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 }}
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.