#1 India's Top IT Training Institute

×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Sorting Algorithms

Quick Sort with Pivot Selection

Quick Sort is a divide-and-conquer sorting algorithm that picks a pivot element and partitions the array so that elements smaller than the pivot come before it and elements larger come after. The choice of pivot heavily influences the algorithm's real-world performance.

Common Pivot Selection Strategies

  • First element: simple, but leads to O(n²) on already sorted arrays.
  • Last element: the classic Lomuto partition scheme.
  • Random element: reduces the chance of worst-case behavior on adversarial input.
  • Median-of-three: picks the median of the first, middle, and last elements for a more balanced split.
import random

def quick_sort(arr, low=0, high=None):
    if high is None:
        high = len(arr) - 1
    if low < high:
        pivot_index = partition(arr, low, high)
        quick_sort(arr, low, pivot_index - 1)
        quick_sort(arr, pivot_index + 1, high)
    return arr

def partition(arr, low, high):
    rand = random.randint(low, high)
    arr[rand], arr[high] = arr[high], arr[rand]   # random pivot
    pivot = arr[high]
    i = low - 1
    for j in range(low, high):
        if arr[j] <= pivot:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]
    arr[i + 1], arr[high] = arr[high], arr[i + 1]
    return i + 1

Complexity

CaseTimeSpace
BestO(n log n)O(log n)
AverageO(n log n)O(log n)
Worst (poor pivot)O(n²)O(n)

Why Pivot Choice Matters

A poor pivot (e.g. always picking the first element on a sorted array) creates highly unbalanced partitions, degrading performance to O(n²). Random or median-of-three pivot selection keeps partitions balanced on average, preserving the O(n log n) behavior in practice.

Ready to master Data Structures & Algorithms?

Learn DSA hands-on with mentor-led sessions, real interview practice, and placement support.

Explore Course