Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quicksort running in O(n^2) time? [duplicate]

Tags:

quicksort

Can anyone explain why the worst-case runtime for quicksort is O(n^2) and why this is rare?

like image 377
John Smith Avatar asked Oct 23 '25 08:10

John Smith


1 Answers

If the pivot is chosen in the worst way every time, rather than partitioning into two lists of size n/2, it will partition into one of size 1 and one of size n-1. This leads to a recursion depth of n and an n^2 total time.

This is rare because the pivot is normally chosen randomly, so the chances of picking the worst pivot every time are small, and on average the pivot will tend to split the list roughly in half.

If the pivot were chosen non-randomly, such as taking the first element, then certain inputs (pre-sorted or reverse-sorted lists) can force n^2 performance.

like image 98
Ryan M Avatar answered Oct 26 '25 00:10

Ryan M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!