4 Partition All the action takes place in the partition() function £ x xRearranges the subarray in placeEnd result: two subarraysAll values in first subarray  all values in secondReturns the index of the “pivot” element separating the two subarrayspqr£ xx≥ x4/8/2017

9 Partition In Words Partition(A, p, r):Select an element to act as the “pivot” (which?)Grow two regions, A[p..i] and A[j..r]All elements in A[p..i] <= pivotAll elements in A[j..r] >= pivotIncrement i until A[i] > pivotDecrement j until A[j] < pivotSwap A[i] and A[j]Repeat until i >= jSwap A[j] and A[p]Return jNote: different from book’s partition(), which uses two iterators that both move forward.4/8/2017

13 Analysis of quicksort Assume all input elements are distinct.In practice, there are better partitioning algorithms for when duplicate input elements may exist.Let T(n) = worst-case running time on an array of n elements.4/8/2017

14 Worst-case of quicksortInput sorted or reverse sorted.Partition around min or max element.One side of partition always has no elements.(arithmetic series)4/8/2017

30 Randomized quicksort Randomly choose an element as pivotEvery time need to do a partition, throw a die to decide which element to use as the pivotEach element has 1/n probability to be selectedRand-Partition(A, p, r)d = random(); // a random number between 0 and 1index = p + floor((r-p+1) * d); // p<=index<=rswap(A[p], A[index]);Partition(A, p, r); // now do partition using A[p] as pivot4/8/2017

About project

Feedback

To ensure the functioning of the site, we use cookies. We share information about your activities on the site with our partners and Google partners: social networks and companies engaged in advertising and web analytics. For more information, see the Privacy Policy and Google Privacy &amp Terms.
Your consent to our cookies if you continue to use this website.