Name: ________________________________

Honor Code Acknowledgment: ___________________


Random Quiz # 8

CPS 100, Spring 1996

Due: February 16


Problem 1: Alfalfa: (5 points)

The partition code below maintains, as an invariant, the picture below

First the "middle" element (see Weiss, page 282) is swapped into the first position, then the vector is partitioned about this new first element. Elements less than or equal to the pivot go to the left, elements greater go to the right, and the index p is the largest index of the less-than-or-equal to section. The Quicksort function is shown too.

You must change Partition so that three sections are used, one section less than the pivot, one section equal to the pivot, and one section greater than the pivot. Partition will be a void function, and return the index of the rightmost less-than element and the index of the leftmost greater-than element via reference parameters. The new header for Partition is

template <class Type> int Partition(Vector<Type> & a,int first,int last, int & less, int & greater) // postcondition: sets less and greater such that // first <= k <= less, a[k] < a[piv] // less < k < greater, a[k] == a[less+1] (the pivot) // greater <= k <= last, a[piv] < a[k] // Here's the original partition code template <class Type> int Partition(Vector<Type> & a,int first,int last) // postcondition: returns piv such that // first <= k <= piv, a[k] <= a[piv] // piv < k <= last, a[piv] < a[k] // { int k,p=first; Type piv; Swap(a,first,Median(a,first,last)); // store "middle" element first piv = a[first]; // will be pivot element for(k=first+1;k<=last;k++) // examine each element { if (a[k] <= piv) // goes in first half { p++; Swap(a,k,p); } } Swap(a,p,first); // put pivot in "middle" return p; } template <class Type> void Quick(Vector<Type> & a,int first,int last) // postcondition: a[first] <= ... <= a[list] { int piv; if (first < last) { piv = Partition(a,first,last); Quick(a,first,piv-1); Quick(a,piv+1,last); } } template <class Type> void QuickSort(Vector<Type> & a, int size) // precondition: size = # of elements of a // postcondition: a is sorted { Quick(a,0,size - 1); }