Quicksort With Median Of Three Pivot (Python)
Sort a list in place using quicksort with median-of-three pivot selection to avoid worst-case on sorted input.
Code
def quicksort(arr, lo=0, hi=None):
if hi is None:
hi = len(arr) - 1
if lo >= hi:
return arr
mid = (lo + hi) // 2
if arr[mid] < arr[lo]:
arr[lo], arr[mid] = arr[mid], arr[lo]
if arr[hi] < arr[lo]:
arr[lo], arr[hi] = arr[hi], arr[lo]
if arr[mid] < arr[hi]:
arr[hi], arr[mid] = arr[mid], arr[hi]
pivot = arr[hi]
i = lo
for j in range(lo, hi):
if arr[j] < pivot:
arr[i], arr[j] = arr[j], arr[i]
i += 1
arr[i], arr[hi] = arr[hi], arr[i]
quicksort(arr, lo, i - 1)
quicksort(arr, i + 1, hi)
return arrInside the snippet
Quicksort With Median Of Three Pivot (Python) is built around the function quicksort.
Iteration happens inside for j in range(lo, hi) — everything outside it runs once.
Putting it to use
The entry-point signature is def quicksort(arr, lo=0, hi=None)
quicksort is the public entry point; everything else in the file exists to support it.
Core lines
if hi is None:
hi = len(arr) - 1
Interactive Tools for This Topic
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. The file defines `quicksort` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.