A killer adversary for quicksort

M. D. McIlroy
1999 Software, Practice & Experience  
Quicksort can be made to go quadratic by constructing input on the fly in response to the sequence of items compared. The technique is illustrated by a specific adversary for the standard C qsort function. The general method works against any implementation of quicksort-even a randomizing one-that satisfies certain very mild and realistic assumptions. When using quicksort one often feels a nagging tension: suppose it goes quadratic? Tactics to avoid embarrassing results in some low-entropy
more » ... , such as already ordered input, are cited in most algorithms books 12 and are widely used. Nevertheless, production implementations have been caught going quadratic in real-life applications. 3 No matter how hard implementers try, they cannot (without great sacrifice of speed) defend against all inputs. This note describes an adversarial method that finds chinks in the defenses of any implementation. A polymorphic implementation of quicksort, such as the standard C function qsort, never looks at the data. It relies instead on an externally supplied comparison function. And that allows us to monitor and influence the program's progress noninvasively. To do so we make a comparison function that observes the pattern of comparisons and constructs adverse data on the fly. Recall that quicksort sorts a sequence of n data items in three phases:
doi:10.1002/(sici)1097-024x(19990410)29:4<341::aid-spe237>3.3.co;2-i fatcat:okub6ggflneftbg4gpxcx6otai