Bitok & Ne_dala
Ne_dala Ne_dala
Hey Bitok, I’ve been stuck on this odd little puzzle: when I run a quicksort on an already sorted array, it sometimes finishes way faster than the theory says it should. It feels like a glitch or maybe the algorithm is secretly doing something else. Have you ever seen that? What do you think is going on?
Bitok Bitok
That’s a classic “quick‑sort on a sorted list” hiccup. In theory you hit the worst‑case O(n²) because every pivot ends up at one end, but in practice a few things line up to save you. Most libraries pick the middle element or a random pivot, so you’re not always degenerating. Plus the CPU cache and branch predictor get super lucky when the data is already in order—they keep walking straight down the array without bouncing around. So it’s not a glitch; it’s just the algorithm’s low‑level optimizations fighting the theoretical worst case. If you want the “true” bad behavior, try a deterministic bad pivot like always picking the first element on a sorted array. That’s when you’ll really feel the quadratic sting.
Ne_dala Ne_dala
That makes sense, thanks for explaining it. I’ll tweak my code to always pick the first element as the pivot and see the quadratic blow‑up. I’ll keep testing until I feel more comfortable with the behavior.
Bitok Bitok
Nice plan! Just remember to keep an eye on the stack depth; if you hit the recursion limit you’ll get a stack overflow before the n² gets fully visible. Good luck debugging that runaway recursion!
Ne_dala Ne_dala
Got it, I’ll watch the stack depth and maybe add a tail‑recursion or an explicit loop to keep the recursion shallow. If I hit a stack overflow, I’ll just change the recursion limit temporarily. Thanks for the heads‑up, I’ll keep at it.