Quick Sort Algorithm: How It Works, Pivot Selection, and Complexity

Last updated by Dipen Dadhaniya on May 28, 2026 at 11:27 AM

Article written by Shashi Kadapa, under the guidance of Neeraj Jhawar, a Senior Software Development Manager and Engineering Leader. Reviewed by Mrudang Vora, an Engineering Leader with 15+ years of experience.

| Reading Time: 3 minutes

Quick sort is used in many systems, such as Java’s Arrays.sort() and Python’s built-in sorting methods. It carries out operations in O(n log n) time, and is efficient in processing large datasets.

In interviews, you are evaluated on quick sort algorithm, and implementation in applications. This blog presents several important concepts and answers to commonly asked questions in quick sort interviews.

What Is Quick Sort?

Q1. What is Quick Sort?

Quick sort is a sorting algorithm that sorts data by choosing a pivot element and splitting the array into two parts: values smaller than the pivot and values larger than it. The same process is then repeated recursively on both sections until the entire array is ordered.

It is widely used because it works in-place, is highly cache-friendly, and delivers strong average-case performance.
When the pivot selection has uneven partitions, the performance reduces. Examples are sorted and improperly arranged input data.

How Quick Sort Works

Q2. How does Quick Sort work step by step?

The steps for quick sort are:

  • Pick a Pivot Element: The first, last, middle elements, a random value can be a pivot.
  • Partition the Array: The array is then rearranged so that all elements smaller than the pivot move to the left side, while larger elements move to the right side. After this step, the pivot lands in its correct sorted position.
  • Sort the Left Subarray: The same process is applied recursively to the left portion of the array containing smaller values.
  • Sort the Right Subarray: Quick sort, then recursively process the right portion containing larger values until the entire array becomes sorted.

Pass-by-pass Dry Run of Quick Sort: The dry run of quick sort is given for example array: [8, 3, 1, 7, 0, 10, 2]. The last element is the pivot.

Pass Pivot Array After Partition
Initial [8, 3, 1, 7, 0, 10, 2]
Pass 1 2 [1, 0, 2, 7, 3, 10, 8]
Pass 2 (Left Side) 0 [0, 1, 2, 7, 3, 10, 8]
Pass 3 (Right Side) 8 [0, 1, 2, 7, 3, 8, 10]
Pass 4 (Subarray) 3 [0, 1, 2, 3, 7, 8, 10]

Key partition invariant rule:

While partitioning, quick sort maintains an important condition:

  • Smaller elements are on the pivot’s left, and larger are on the right
  • Pivot cannot be moved after placement.

This rule allows quick sort to break the problem into smaller, independent parts, making the algorithm fast and efficient for large datasets.

Quick Sort Dry Run Table

Array: [8, 3, 1, 7, 0, 10, 2]. Pivot = last element (2).

Step Array State Action
Initial [8, 3, 1, 7, 0, 10, 2] Pivot selected: 2 (last element)
After partition [0, 1, 2, 7, 3, 10, 8] Pivot (2) in final position. Left: [0,1]. Right: [7,3,10,8]
Recurse left [0, 1] Already sorted – base case
Recurse right [3, 7, 8, 10] Recursively sorted
Final [0, 1, 2, 3, 7, 8, 10] Sort complete
📝 Note: After partitioning, the pivot is in its final sorted position permanently; it never moves again. Understanding this invariant is what separates a complete explanation from a superficial one.

Pivot Selection Strategies

Q3. How do you choose a pivot in quicksort?

Pivot breaks up the array into parts. A pivot can be picked from the beginning, end, middle, or even randomly from the array. Smarter choices, such as a random pivot or median-of-three, often lead to better balance and faster sorting. The following table shows some of the quic

Strategy Process of working Advantages It fails when …
First element Always use arr[0] as pivot Simple to implement Worst case O(n squared) on sorted or reverse-sorted arrays
Last element Always use arr[n-1] as pivot Simple to implement Same worst case as first element on sorted input
Random element Choose a random index as pivot Avoids worst case in practice Requires random number generation
Median of three Use median of first, middle, last elements Best practical performance Slightly more complex to implement
📝 Note: The most common interview question about quicksort is ‘what is the worst case and when does it occur?’ The answer is always about pivot selection: when the pivot consistently lands at one extreme of the partition (always picking the smallest or largest remaining element), the recursion tree becomes linear rather than balanced. Random pivot or median-of-three avoids this in practice.

Quick Sort Algorithm and Code

Q4. What are the steps of the quick sort algorithm?

The steps are:

  • Pick a pivot element from the array. The pivot may be the first, last, middle, or any randomly selected value.
  • Use the partition step to arrange the elements. Values smaller than the pivot are moved to the left, while greater values are placed on the right.
  • After partitioning, the pivot reaches its correct position in the sorted array.
  • Repeat the quick sort process on the left part of the array containing smaller elements.
  • Repeat the same process on the right part containing larger elements until every section is fully sorted.

Q5. What is the pseudocode for quick sort?

Quick Sort is a divide-and-conquer sorting algorithm that works by selecting a pivot element and arranging the array around it. The partition function places smaller elements on one side of the pivot and larger elements on the other. The quickSort function then recursively sorts the left and right subarrays.

Algorithm quickSort(arr, low, high)
  If low < high
    pivotIndex = partition(arr, low, high)
    quickSort(arr, low, pivotIndex - 1)
    quickSort(arr, pivotIndex + 1, high)

Algorithm partition(arr, low, high)
  pivot = arr[high]
  i = low - 1
  For j = low to high - 1
    If arr[j] < pivot
      i = i + 1
      Swap arr[i] and arr[j]
  Swap arr[i + 1] and arr[high]
  Return i + 1

Q6. Quick Sort Program in Python

Python offers a clean and readable way to implement Quick Sort. The algorithm works by selecting a pivot element, dividing the array into smaller sections, and recursively sorting each part.

The example below includes both the quickSort() function and the partition() helper function.

def partition(arr, low, high):
    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


def quickSort(arr, low, high):
    if low < high:
        pivotIndex = partition(arr, low, high)

        quickSort(arr, low, pivotIndex - 1)
        quickSort(arr, pivotIndex + 1, high)


# Driver code
arr = [8, 3, 1, 7, 0, 10, 2]

quickSort(arr, 0, len(arr) - 1)

print("Sorted Array:", arr)

Q7. Quick Sort Program in Java

Java uses methods and classes to organize the Quick Sort algorithm. The partition() method places the pivot in its correct position, while the quickSort() method recursively sorts the remaining elements.

class QuickSort {

    int partition(int arr[], int low, int high) {

        int pivot = arr[high];
        int i = low - 1;

        for (int j = low; j < high; j++) {

            if (arr[j] < pivot) {
                i++;

                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }

        int temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;

        return i + 1;
    }

    void quickSort(int arr[], int low, int high) {

        if (low < high) {

            int pivotIndex = partition(arr, low, high);

            quickSort(arr, low, pivotIndex - 1);
            quickSort(arr, pivotIndex + 1, high);
        }
    }

    void printArray(int arr[]) {

        for (int num : arr) {
            System.out.print(num + " ");
        }
    }

    public static void main(String[] args) {

        int arr[] = {8, 3, 1, 7, 0, 10, 2};

        QuickSort obj = new QuickSort();

        obj.quickSort(arr, 0, arr.length - 1);

        System.out.println("Sorted Array:");
        obj.printArray(arr);
    }
}

Q8. Quick Sort Program in C++

C++ is commonly used for implementing efficient sorting algorithms because of its speed and memory control. The following example shows a complete Quick Sort implementation with separate partition and recursive sorting functions.

#include <iostream>
using namespace std;

int partition(int arr[], int low, int high) {

    int pivot = arr[high];
    int i = low - 1;

    for (int j = low; j < high; j++) {

        if (arr[j] < pivot) {
            i++;

            swap(arr[i], arr[j]);
        }
    }

    swap(arr[i + 1], arr[high]);

    return i + 1;
}

void quickSort(int arr[], int low, int high) {

    if (low < high) {

        int pivotIndex = partition(arr, low, high);

        quickSort(arr, low, pivotIndex - 1);
        quickSort(arr, pivotIndex + 1, high);
    }
}

void printArray(int arr[], int size) {

    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
}

int main() {

    int arr[] = {8, 3, 1, 7, 0, 10, 2};

    int size = sizeof(arr) / sizeof(arr[0]);

    quickSort(arr, 0, size - 1);

    cout << "Sorted Array: ";

    printArray(arr, size);

    return 0;
}

Quick Sort Time and Space Complexity

Q9. What is the time complexity of quick sort?

Quick Sort gives fast performance with large datasets and is implemented used in many applications. Its efficiency depends on how evenly the array is divided during each partition step. In most situations, Quick Sort performs very well, but poor pivot selection can lead to slower execution. The following is a quick sort complexity table:

Case Time Complexity When It Occurs Why
Best case O(n log n) Pivot always lands near the middle Recursion tree is balanced – log n levels, each O(n) work
Average case O(n log n) Random or well-distributed input Balanced enough on average – same structure as best case
Worst case O(n squared) Pivot always min or max remaining element Recursion tree becomes linear – n levels, each O(n) work
Space O(log n) Average case call stack depth In-place – no auxiliary array, but recursion uses stack space
📝 Note: When the pivot is always the minimum or maximum remaining element which happens on sorted input when first or last element is always chosen. The fix is random pivot or median-of-three.

Q10. Is quick sort stable and in-place?

Quick Sort is generally treated as an in-place sorting algorithm because it sorts the elements within the original array itself. It does not need an extra array for processing, and the additional memory usage mainly comes from recursive function calls. On average, the recursion stack requires about O(log n) space.

The standard implementation of Quick Sort is not stable. While partitioning the array, elements with the same value can be swapped into different positions, changing their original order. Because of this behavior, equal elements may not remain in the same sequence after sorting.

Although stable versions of Quick Sort do exist, they usually require extra memory or more complex partitioning techniques. This makes the algorithm harder to implement compared to the traditional version. It is also a common interview question to ask whether Quick Sort is stable and in-place, especially when comparing it with algorithms such as Merge Sort.

Lomuto vs Hoare Partition Schemes

Q11. What is the difference between Lomuto and Hoare partition schemes?

Two popular partitioning techniques in Quick Sort are Lomuto and Hoare. Although they both split the array around a pivot element, their methods for scanning and exchanging elements differ. Performance, swap count, and efficiency on various input data types can all be impacted by the partition scheme selection. The following table compares Lomuto and Hoare partition schemes.

Aspect Lomuto Partition Hoare’s Partition
How it works One pointer from left, swaps smaller elements toward front Two pointers from both ends, swap when out of order
Pivot placement Pivot ends up in its final position after partition Pivot does not necessarily end up in final position
Number of swaps More swaps on average Fewer swaps on average – more efficient
Code complexity Simpler to understand and implement Slightly more complex
Common usage Teaching and beginner implementations Production implementations
Worst case input Sorted array with last element as pivot Sorted array with first element as pivot

The method of the Lomuto partition scheme places smaller elements ahead of the pivot by scanning the array from left to right. The pivot is switched to its proper position at the conclusion. It is frequently used in instructional examples and coding interviews because the concept is simple.

Two pointers that approach one another from both sides of the array are used in the Hoare partition scheme. Elements are instantly switched if they are discovered on the incorrect side.

Quick Sort vs Merge Sort

Q12. How does quick sort compare to merge sort?

Quick Sort and Merge Sort are two of the most widely used sorting algorithms. Both follow the divide-and-conquer approach, where the problem is broken into smaller parts and solved recursively. Even though their average performance is similar, they differ in memory usage, stability, and behavior in worst-case situations. The following table provides a comparision between quick & merge sort.

Aspect Quick Sort Merge Sort
Average time O(n log n) O(n log n)
Worst case O(n squared) – bad pivot O(n log n) – always
Space O(log n) – call stack only O(n) – auxiliary array
Stable? No Yes
Cache performance Better – in-place sequential access Worse – auxiliary array causes cache misses
Best for General in-memory sorting of large arrays Linked lists, external sort, when stability required

Also Read: Time Complexities of All Sorting Algorithms

Quick Sort Interview Patterns

Q13. In which interview problems does quick sort appear?

Quick sort frequently appears in technical interviews because it combines sorting, recursion, and partitioning concepts in one algorithm. Interviewers use quick sort–based problems to check how candidates handle arrays, optimize performance, and think through edge cases.

Questions such as finding the kth largest element or rearranging numbers around a pivot are commonly inspired by quick sort. Even when the algorithm itself is not asked directly, its core ideas are often part of problem-solving discussions.

Pattern How Quicksort Applies Example Problems
Sort in place Standard quicksort – partition and recurse without auxiliary array LeetCode 912: Sort an Array
QuickSelect (Kth element) Partition step finds pivot’s final position – only recurse on the side containing K LeetCode 215: Kth Largest Element in Array
Dutch National Flag Three-way partition for arrays with 3 distinct values (0s, 1s, 2s) LeetCode 75: Sort Colors
Partial sort Use QuickSelect to find top-K elements without fully sorting Top K frequent elements pattern
📝 Note: QuickSelect uses the partition step from quicksort to find the Kth smallest element in O(n) average time without sorting the entire array. It is one of the most frequently asked patterns in FAANG interviews because it combines partitioning logic with the concept of not doing unnecessary work. Candidates who know QuickSelect demonstrate understanding of the core partition invariant, not just the sorting algorithm.

Conclusion

This blog examined several important topics in quick sort. Quick sort algorithms and how quick sort works were examined with examples. Pivot selection strategies in quick sort, pseudocode, and quick sort programs in Java, Python, and C# were discussed.

Quick sort offers O(n log n) average performance, works in-place, and is widely used for sorting large arrays in memory. Understanding concepts like worst-case behavior, pivot selection, and QuickSelect helps build deeper algorithmic knowledge instead of simple memorization. These topics are also highly important for strong FAANG Interview Preparation and technical coding interview success.

FAQs: Quick Sort

Q1. Why is quick sort faster than merge sort in practice?

Quick sort is often faster because it sorts within the same array, improving cache efficiency and reducing extra memory usage compared to merge sort.

Q2. Is quick sort used in real-world systems?

Yes, many real-world systems use optimized versions of quick sort because of its speed and efficiency on large datasets.

Q3. What is the difference between quicksort and quickselect?

Quicksort sorts the entire array, while QuickSelect finds only the required kth element, making it faster for selection problems.

Last updated on: May 28, 2026
Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Strange Tier-1 Neural “Power Patterns” Used By 20,013 FAANG Engineers To Ace Big Tech Interviews

100% Free — No credit card needed.

Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

IK courses Recommended

Master ML interviews with DSA, ML System Design, Supervised/Unsupervised Learning, DL, and FAANG-level interview prep.

Fast filling course!

Get strategies to ace TPM interviews with training in program planning, execution, reporting, and behavioral frameworks.

Course covering SQL, ETL pipelines, data modeling, scalable systems, and FAANG interview prep to land top DE roles.

Course covering Embedded C, microcontrollers, system design, and debugging to crack FAANG-level Embedded SWE interviews.

Nail FAANG+ Engineering Management interviews with focused training for leadership, Scalable System Design, and coding.

End-to-end prep program to master FAANG-level SQL, statistics, ML, A/B testing, DL, and FAANG-level DS interviews.

Select a course based on your goals

Learn to build AI agents to automate your repetitive workflows

Upskill yourself with AI and Machine learning skills

Prepare for the toughest interviews with FAANG+ mentorship

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Almost there...
Share your details for a personalised FAANG career consultation!
Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!

Registration completed!

🗓️ Friday, 18th April, 6 PM

Your Webinar slot

Mornings, 8-10 AM

Our Program Advisor will call you at this time

Register for our webinar

Transform Your Tech Career with AI Excellence

Transform Your Tech Career with AI Excellence

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

25,000+ Professionals Trained

₹23 LPA Average Hike 60% Average Hike

600+ MAANG+ Instructors

Webinar Slot Blocked

Interview Kickstart Logo

Register for our webinar

Transform your tech career

Transform your tech career

Learn about hiring processes, interview strategies. Find the best course for you.

Loading_icon
Loading...
*Invalid Phone Number

Used to send reminder for webinar

By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!
Registration completed!
🗓️ Friday, 18th April, 6 PM
Your Webinar slot
Mornings, 8-10 AM
Our Program Advisor will call you at this time

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Your PDF Is One Step Away!

The 11 Neural “Power Patterns” For Solving Any FAANG Interview Problem 12.5X Faster Than 99.8% OF Applicants

The 2 “Magic Questions” That Reveal Whether You’re Good Enough To Receive A Lucrative Big Tech Offer

The “Instant Income Multiplier” That 2-3X’s Your Current Tech Salary

Transform Your Tech Career with AI Excellence

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

Webinar Slot Blocked

Loading_icon
Loading...
*Invalid Phone Number
By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Registration completed!

See you there!

Webinar on Friday, 18th April | 6 PM
Webinar details have been sent to your email
Mornings, 8-10 AM
Our Program Advisor will call you at this time