QuickSort: Explanation and Implementation

Want to dive deeper into sorting algorithms and other essential DSA concepts? Sign up for free course updates to access exclusive resources and stay ahead in your learning journey. Whether you’re preparing for interviews or sharpening your coding skills, structured guidance can make all the difference.

What is QuickSort?

QuickSort is a divide-and-conquer algorithm invented by Sir Tony Hoare in 1959. It’s one of the fastest sorting methods, widely used in programming languages like Python and JavaScript for its efficiency. Unlike MergeSort, which splits arrays into equal halves, QuickSort uses a pivot element to partition data dynamically.

Key Features of QuickSort

  • Average Time Complexity: O(n log n)
  • In-Place Sorting: Modifies the original array, minimizing memory usage.
  • Unstable Sorting: Doesn’t preserve the order of equal elements.

Quote: Tony Hoare once said, “The idea [of QuickSort] is to divide the problem into smaller parts and conquer them recursively.”

Algorithm

Average Time

Space Complexity

Stability

QuickSort

O(n log n)

O(log n)

No

MergeSort

O(n log n)

O(n)

Yes

BubbleSort

O(n²)

O(1)

Yes

How Does QuickSort Work?

QuickSort works by selecting a pivot element and rearranging the array so elements smaller than the pivot are on its left, and larger ones are on the right. This process, called partitioning, repeats recursively until the entire array is sorted.

Partitioning Process

  1. Choose a Pivot: Often the last or middle element.
  2. Rearrange Elements: Move smaller elements left and larger ones right of the pivot.
  3. Recurse: Repeat for the left and right subarrays.

For example, sorting [3, 6, 8, 2, 1] with a pivot of 1 would first split the array into [] (left) and [3, 6, 8, 2] (right), then progressively sort smaller segments.

How Does QuickSort Work

How Does QuickSort Work?

QuickSort works by selecting a pivot element and rearranging the array so elements smaller than the pivot are on its left, and larger ones are on the right. This process, called partitioning, repeats recursively until the entire array is sorted.

Partitioning Process

  1. Choose a Pivot: Often the last or middle element.
  2. Rearrange Elements: Move smaller elements left and larger ones right of the pivot.
  3. Recurse: Repeat for the left and right subarrays.

For example, sorting [3, 6, 8, 2, 1] with a pivot of 1 would first split the array into [] (left) and [3, 6, 8, 2] (right), then progressively sort smaller segments.

Time and Space Complexity of QuickSort

Best and Worst-Case Scenarios

  • Best Case: Pivot divides the array evenly → O(n log n).
  • Worst Case: Pivot is the smallest/largest element → O(n²).

Stat: In practice, QuickSort is 2-3 times faster than MergeSort due to better cache performance (Source: Stanford University Analysis).

Comparing QuickSort with Other Algorithms

Scenario

QuickSort

MergeSort

HeapSort

Large Datasets

Excellent

Good

Fair

Memory Constraints

Ideal

Poor

Good

Stability

No

Yes

No

For coding interviews, understanding these trade-offs is critical. Top Amazon DSA Interview Questions often test this knowledge.

Implementing QuickSort in Code

Pseudocode Breakdown

				
					function quicksort(arr):
    if length(arr) ≤ 1:
        return arr
    pivot = select_pivot(arr)
    left, right = partition(arr, pivot)
    return quicksort(left) + [pivot] + quicksort(right)

				
			

Python Example

				
					def quicksort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[-1]
    left = [x for x in arr[:-1] if x <= pivot]
    right = [x for x in arr[:-1] if x > pivot]
    return quicksort(left) + [pivot] + quicksort(right)

				
			

JavaScript Example

				
					function quicksort(arr) {
    if (arr.length <= 1) return arr;
    const pivot = arr[arr.length - 1];
    const left = [];
    const right = [];
    for (const x of arr.slice(0, -1)) {
        (x <= pivot) ? left.push(x) : right.push(x);
    }
    return [...quicksort(left), pivot, ...quicksort(right)];
}

				
			

To master coding implementations, enroll in our DSA Course, which includes hands-on projects and interview drills.

Optimizing QuickSort for Real-World Use

Choosing the Right Pivot

  • Random Pivot: Reduces worst-case risk.
  • Median-of-Three: Picks the median of the first, middle, and last elements.
Optimizing QuickSort for Real-World Use

Handling Repeated Elements

Use a 3-way partitioning (Dutch National Flag method) to group duplicates together, reducing redundant comparisons.

Case Study: Python’s sorted() function uses a hybrid of QuickSort and InsertionSort for small datasets.

For advanced optimization strategies, explore our Master DSA & Web Development Course, which covers system design principles.

Handling Repeated Elements

How can mastering data structures and algorithms accelerate my interview success?

Data structures and algorithms are the backbone of most coding interviews—practicing them builds problem-solving speed and confidence. Elevate your skills with our hands-on Data Structures & Algorithms course.

Combining algorithmic thinking with web development lets you build dynamic, high-performance applications from front end to back end. Get started with our immersive Web Development course.

Yes—bridging creative UI/UX design with advanced algorithmic logic makes you a more versatile developer. Check out the integrated Design & DSA Combined course to boost both skill sets.

This all-in-one curriculum covers essential algorithms, full-stack development, and scalable system architecture to prepare you for senior roles. Level up with our Master DSA + Web Dev + System Design course.

Data science empowers you to extract insights, build predictive models, and make data-driven decisions. Dive into our expert-led Data Science course to merge coding with analysis.

DSA, High & Low Level System Designs

Buy for 60% OFF
₹25,000.00 ₹9,999.00

Accelerate your Path to a Product based Career

Boost your career or get hired at top product-based companies by joining our expertly crafted courses. Gain practical skills and real-world knowledge to help you succeed.

Reach Out Now

If you have any queries, please fill out this form. We will surely reach out to you.

Contact Email

Reach us at the following email address.

arun@getsdeready.com

Phone Number

You can reach us by phone as well.

+91-97737 28034

Our Location

Rohini, Sector-3, Delhi-110085

WhatsApp Icon

Master Your Interviews with Our Free Roadmap!

Hi Instagram Fam!
Get a FREE Cheat Sheet on System Design.

Hi LinkedIn Fam!
Get a FREE Cheat Sheet on System Design

Loved Our YouTube Videos? Get a FREE Cheat Sheet on System Design.