Quick Sort in Python: Algorithm, Working, Code, Time & Space Complexity

What Is QuickSort In Python?

Are you working with large datasets that need to be sorted efficiently? If so, “Quick Sort in Python” is one of the most effective sorting algorithms. 

Among the various sorting techniques studied in Data Structures and Algorithms, Quick Sort is widely known for its speed and efficiency. This article focuses on implementing the Quick Sort algorithm using Python. 

Before diving into the implementation, it is important to understand the basic concepts behind the Quick Sort algorithm. Let us begin by exploring the fundamentals of sorting algorithms in computer science.

TL;DR: Quick Sort In Python

Aspect

Summary

What is Quicksort?

Quicksort is a divide-and-conquer sorting algorithm that sorts elements by choosing a pivot and partitioning the array around it.

Why Students Find It Confusing

Students struggle because pivot selection, partitioning, and recursion are introduced together without enough visualization. 

Role of Pivot

The pivot helps divide the array into smaller and larger elements and is placed in its final sorted position during partitioning. 

Time & Space Complexity

Quicksort runs in O(n log n) time on average but can degrade to O(n²) in the worst case with poor pivot choices. Space complexity is generally O(log n).

When Not to Use

Quicksort is not ideal when stable sorting is required or when the data is already nearly sorted. It should also be avoided when predictable performance is critical.

What is a Sorting Algorithm & Its Different Types? Get To Know

In computer science, there is a special section on the Data Structure topic. The section is known as the Sorting Algorithm section. There are likely nine different sorting algorithms present. Now, as a developer, you should choose a particular algorithm to solve any problem.

Different sorting algorithms take different times to solve different problems. So, picking up the most appropriate sorting algorithm will be a difficult task for the developer. There are many algorithms. They all have different strategies to sort the giving sequence. Like there are Bubble sort algorithms, Heap sort algorithms, etc.

What Is Quicksort In Python Programming Language? Read Below

The Quicksort algorithm depends upon the strategy of Divide & Conquer.  That means a large set of data will be first divided into some small pieces. Now, those small pieces will be evaluated & at the end, they will be again combined to get the full result.

“Mastering divide and conquer strategies is essential for optimizing algorithm performance; if you need help analyzing these complexities, our experts can assist you.”

Following the same manner, the Quicksort algorithm first divides a set of elements into two pieces. Now, those two pieces will again be divided into two small pieces. In this way, when the pieces become very small they are calculated.

In the end, all those results are merged & the final result is produced. The element by which the basis of the division of the element set happens is known as the Pivot element in the Quicksort algorithm.

Python Homework Help

Why Students Find Quicksort Confusing At First?

Quicksort often feels confusing to students during their first exposure because multiple abstract concepts are introduced at the same time, without enough real-world context. 

From years of observing student mistakes and exam answers, these are the most common reasons:

1) Confusion With The Partition Logic:

Many students struggle with Quicksort because the partition step is not intuitive. They often confuse which elements go left or right of the pivot, and why the pivot ends up in a sorted position.

				
					def partition(arr, low, high):
    pivot = arr[high]  # choose last element as pivot
    i = low - 1        # pointer for smaller elements
    for j in range(low, high):
        if arr[j] <= pivot:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]  # swap smaller element
    arr[i+1], arr[high] = arr[high], arr[i+1]  # place pivot
    return i+1

				
			

The confusion arises because students don’t see why elements are swapped or where the pivot belongs. Partitioning is the core step; misunderstanding it makes the whole sort seem magical.

2) Recursion Feels Like A Black Box:

Quicksort uses recursion heavily, and beginners often cannot visualize how the array gets divided and conquered step by step.

				
					def quicksort(arr, low, high):
    if low < high:
        pi = partition(arr, low, high)  # divide array
        quicksort(arr, low, pi-1)       # sort left
        quicksort(arr, pi+1, high)      # sort right

				
			

Students often think all sorting happens at once, not realizing that each recursive call sorts only a subarray. This leads to confusion about why the algorithm eventually sorts the entire array.

3) Confusing In-Place Swaps With New Arrays: 

Unlike some other sorting methods, Quicksort does not create new arrays. Beginners expect a fresh array after each operation and get confused when the same array changes in place.

				
					arr = [3,6,8,10,1,2,1]
quicksort(arr, 0, len(arr)-1)
print(arr)  # array is now sorted

				
			

Students often expect a return value for the sorted array. In reality, Quicksort modifies the original array, which can be surprising if they are used to functional-style Python methods.

Expert Tip: Once students manually trace just one full run of Quicksort, their confusion usually disappears.

What Are The Steps In Quicksort Algorithm?

 Steps

While teaching sorting algorithms, I’ve noticed that many students understand the idea of sorting, but feel stuck when Quicksort introduces pivot selection and recursion together.

So, we should pay attention to the steps required for the Quicksort algorithm. The required steps are as follows:

  • Choose Pivot:

At first, the pivot element should be declared inside the program. Here, the pivot element can be any element from the set provided in the program. But mainly, the first or last element is chosen as the pivot element. Sometimes, the middle element can also be chosen.

  • Divide:

After getting the Pivot element, we should break down the list of elements into two parts. The one part will be on the left side of the Pivot element. And another will be on the right side of the Pivot element. Now, these two parts have been taken into consideration.

Inside those two sub-parts, the pivot element will again be picked up. And based upon that pivot element, those sub-parts will again divide into the smaller sub-parts. In this way, the complete process will be executed.

  • Recursion:

The same process will be followed recursively after & after till we do not receive any sub-parts having only two or three elements. Now, those elements will be sorted & the result sub-part will be produced.

  • Conquer:

At last, all the mini sub-parts are going to merge. Hence, the total list of elements is now present in front of the programmer. Hence, there are no more tasks present to complete the Quicksort algorithm.

How Does Quicksort Work?

Suppose, there is an array of elements present like the {1, 4, 2, 5, 3}. Now, we have to pick up the Pivot Element from that array. We are going to pick up the Last Element 3 as the Pivot Element.

Quick Sort Steps

Now, based on the Pivot Element, there will be two different arrays will be developed. In one array, there will be data in the sequence as like {1, 2} as Element 2 is present after Element 1. And another array will have the data as like {4, 5} with the same logic.

Now, we can further again divide those two smaller arrays with the last element as Pivot One. But, as they are already present in the correct sorted manner, we are skipping the step. Now, the Pivot Element will be placed at the right spot.

Quick Sort Step 2

In the end, all the elements of different arrays will be merged to make the new sorted array with Quick Sort.

What Is the Role Of Pivot In Quicksort?

From an academic point of view, most Quicksort errors occur not in recursion, but in misunderstanding how the pivot is placed correctly during partitioning.

The pivot is the heart of the Quicksort algorithm, and understanding its role clearly can instantly improve a student’s confidence with this topic.

The pivot is the element chosen to divide the array into two logical parts. They are the: Elements smaller than the pivot and Elements greater than or equal to the pivot.

The pivot decides how efficiently Quicksort performs.

  • A good pivot divides the array into almost equal halves
  • A bad pivot creates very unbalanced subarrays

Pivot Choice

Effect

First element

Simple to implement, but may cause poor performance for sorted lists

Last element

Easy to use and commonly taught, but still vulnerable to worst-case scenarios

Random pivot

Reduces the chance of worst-case time complexity and improves balance

Middle element

Helps avoid highly unbalanced partitions and reduces the worst-case input

During partitioning, the pivot is placed in its correct final position, meaning it will not move again in the rest of the algorithm. This is why Quicksort works without explicitly merging arrays like Merge Sort.

From an academic and practical point of view:

  • A well-chosen pivot leads to balanced subarrays and faster execution.
  • A poor pivot choice can cause highly unbalanced partitions and poor performance.
  • Exam questions often assume the first or last element as the pivot for simplicity.

Exam Tip: Many students lose marks not because of wrong logic, but because they fail to explain pivot placement clearly in words.

What Is The Pseudo-Code Of The Quicksort Algorithm In Python Programming Language?

Pseudo-codes are not complete code nor is it following any programming languages for the implementation process. With any normal textual language, it can be defined. The goal is to find out the complete workflow of the program.

So, the Pseudo-code of the Quicksort algorithm is following:

				
					function-quicksort(arr)
check length(arr) <= 1
back arr
otherwise: change pivot = arr[0]
change left side = Null array
change right side = Null array
for each element ele in arr[1:]
check ele < pivot
add ele to left side
otherwise: add ele to right side
call again function-quicksort(left side)
call again function-quicksort(right side)
back all data


				
			

Now, after discussing the Pseudo-code of the Quicksort algorithm, we are free to move for the implementation process using the Python.

How To Implement The Quicksort Python Code Easily?

The development of the Quick Sort Algorithm is not a challenging task. You have to remember the policy to make the partition in the code.

And the logic to make the partition in the code, you can get from the Pseudo-Code that is being discussed earlier. One thing that is more attractive in Python Quick Sort, is that there is no need to import any package in the program to work on the process.

Python Program To Demonstrate The Implementation Process Of Quick Sort:

				
					def qsort(x): # Declaration Of The Function


    if len(x) <= 1: # Checking The Length or End Condition
     return x # Returning The Value
    else: # For Other Condition
        p = x[0] # Getting Pivot Value
        l = [k for k in x[1:] if k < p] # Generating Left Sub Array
        r = [k for k in x[1:] if k >= p] # Generating Right Sub Array
        return qsort(l) + [p] + qsort(r) # Recursively Calling The Function
a = [4, 2, 7, 2, 1] # Assigning The Unsorted String Value
print(“Unsorted Array: “, a) # Printing The Original Element
b = qsort(a) # Calling The Function
print(“Sorted Array: “, b) # Printing The Elements

				
			

Steps Of The Program: 

  • First, we have to declare the array with some natural numbers placed in random order.
  • Then, the Unsorted Array will be printed in the output.
  • Then, the Quick Sort Function will be called in the program where the Array will be shared.
  • In the Quick Sort Function, the First Element will be chosen as the Pivot Element.
  • One For Loop will be executed to check lower values from the Pivot Element. And made a Left Subarray.
  • By using the same manner, all the higher values than the Pivot Element will be stored in the Right Subarray.
  • Now, the Quick Sort Function will be called in the Return Statement where as per the Rule, the Pivot Element is placed in between the Left Subarray & Right Subarray.
  • At last, the new array will be printed in the Python Code.

Let us try to find out the output of the above code. It will help to understand the implementation process of the Quicksort algorithm in Python programming language.

Output:

Output

From the above output, we can see that the Unsorted Array is now become a sorted one. All the elements in the Unsorted Array, even the repetitive Element 2 are placed in the correct position. So, the Python Code works completely fine.

“Handling large datasets requires optimized code; if your sorting script is running too slowly, our team can refactor your Python algorithms for maximum efficiency.”

What Are The Time & Space Complexity Of Quick Sort Algorithm?

The Time Complexity of the Quick Sort Algorithm for the Average Case will be O(N Log N). And for the worst cases, the Time Complexity can go up to O(N^2). So, we can understand the Quick Sort Algorithm is taking time efficiently.

Now, it is time to discuss the Space Complexity of the Quick Sort Algorithm. The Space Complexity of the Quick Sort Algorithm will be the O(Log N) for average cases. And for the worst cases, the Space Complexity will be the O(N).

Indexing in Python lists may present challenges, and to tackle this issue, we’ve developed a detailed article aimed at enhancing your understanding.

What Is The Role Of Recursion In Quick Sort Algorithm?

Recursion is the pillar of the Quicksort algorithm process. Without the recursion method, we can’t implement the Quicksort algorithm in Python programming language.

Recursion is a method that calls the same function again & again time from the said function only. In this way, some processes are completed. It works similarly to the loop concept, but it takes small space.

Now, you might ask Can Quicksort Algorithm be Implemented Without Using the Recursion Method?

Yes! The Quicksort algorithm can be implemented without using the recursion method. Other sorting algorithms can also be implemented without using the same. But in that case, they will take a long time to get the solution to the problem.

In those cases, we should develop one for loop to check & divide the set of elements in the program. This is the reason, instead of using the iteration method; the recursion method is used highly in the sorting algorithms.

Real Assignment Question: Implementing Quick Sort Without Recursion

We have seen many times in lab exams that students are often asked to implement quicksort without recursion. As explicitly mentioned in “Without Recursion, students have to follow an iterative approach.

This is where students get stuck, as they have never practiced it. Here is the way to implement Quicksort without recursion.

				
					def iterative_quicksort(arr):
    # Create A Stack To Store Start And End Indices
    stack = [(0, len(arr) - 1)]

    while stack:
        low, high = stack.pop()   # Get The Current Subarray Range

        # Continue Only If There Are At Least Two Elements
        if low < high:
            pivot = arr[high] # Choose Last Element As Pivot
            i = low - 1

            # Rearrange Elements Based On Pivot
            for j in range(low, high):
                if arr[j] <= pivot:
                    i += 1
                    arr[i], arr[j] = arr[j], arr[i]

            # Place Pivot In Correct Position
            arr[i + 1], arr[high] = arr[high], arr[i + 1]
            p = i + 1  # Pivot Index

            # Push Left And Right Subarrays To Stack
            stack.append((low, p - 1))
            stack.append((p + 1, high))


nums = [5, 2, 9, 1] # Unsorted Arrays
iterative_quicksort(nums)
print("Quick Sort Without Recursion")
print("Sorted List:", nums)

				
			

Here, a stack is used instead of function calls. And the last element is chosen as the pivot. All the elements smaller than pivot go to the left, and the elements greater than pivot go to the right.

The array is sorted in place, and this method uses less memory than recursive Quick Sort. Iterative Quick Sort replaces recursion with a stack and sorts the array in place.

Output file for quick sort problem without using recursion.

How Fast Is Quicksort? Read Below

Before ending the topic, we want to discuss this one of the important questions. Sometimes, you can face the question “Is Heap Sort Faster than Quicksort?”. In all similar questions, put the Answer as YES!

The Quick Sort is one of the most important sorting algorithms that is considered the fastest. Because, the inner loop of the Quick Sort Algorithm where the For Loop is mainly used, consumes more small spaces & statements. That is the reason, Quick Sort can perform well.

On the other hand, Sorting Algorithms like Heap Sort take 4 times more statements in the For Loop before going for the execution. That is the reason, the Time Complexity of Quick Sort is the same for both Best & Average Cases.

What Are Advantages & Disadvantages Of Quick Sort Algorithms?

Advantages Of Quick Sort Algorithm:

  • It is faster than any other sorting algorithm. 
  • For Large Datasets, it will be best suited to the sorting algorithm.
  • The Quick Sort Algorithm is mainly used for real-world applications.

Disadvantages Of Quick Sort Algorithm:

  • The worst-case time complexity is relatively too high which depends on pivot choosing.
  • The Quick Sort is not suitable for the dataset which is relatively too short.
  • The Quick Sort is an unstable sorting algorithm that sometimes causes problems.

When Should Students Not Use Quicksort In Python?

Our expertise says that, as Quicksort is a fast and popular sorting algorithm, students tend to use Quicksort in every situation. This practice often leads to marks being lost in exams and assignments.

Here are the situations when you should avoid using Quicksort in Python.

  • When you need a stable sorting algorithm, Quicksort does not preserve the order of equal elements.
  • When the input data is already nearly sorted, this can trigger the worst-case time complexity.
  • When consistent performance is critical, and O(n²) behavior cannot be tolerated.
  • When working with small datasets, simpler algorithms like Insertion Sort perform just as well with less overhead.
  • When recursion depth is a concern, especially in Python, where deep recursion may cause stack overflow errors.

Although Quicksort is efficient on average, its performance depends heavily on pivot choice, which is why it is not always the safest option in every scenario.

Common Mistakes Students Make In Python Quicksort Assignments:

Though Quicksort is not a complicated sorting algorithm, we have noticed for a long time that students often commit some common mistakes while working with it.

Based on common exam scripts, assignments, and lab submissions, the following mistakes appear repeatedly among students.

  • Forgetting to include a proper base condition leads to infinite recursion or runtime errors.
  • Misunderstanding pivot placement and assuming the pivot gets sorted after recursion instead of during partitioning.
  • Writing incorrect recursive calls by passing wrong index ranges in in-place implementations.
  • Assuming Quicksort always runs in O(n log n) time and ignoring the worst-case scenario.
  • Confusing Quicksort with Merge Sort and incorrectly mentioning a merge step in explanations.

Conclusion:

As we saw, the “Quick Sort in Python” programming language is very important to know.

By understanding why Quicksort works rather than memorizing its steps, students can confidently explain the algorithm in exams and apply it correctly in Python programs.

If you are preparing for exams, focus more on explaining pivot behavior and partitioning steps clearly, as these are commonly evaluated rather than writing fully optimized code.

So, hope you have liked this piece of article. Share your thoughts in the comments section and let us know if we can improve more.

Takeaways:

  • The main element of the Quick Sort Algorithm is to pick up the Pivot Element.
  • Based on the Pivot Element, the Time Complexity can be different.
  • The Partition Module of Quick Sort is developed on the Pivot Element Selection.
  • The Quick Sort Algorithm follows the Divide and Conquer Policy. If you’re looking for more Python sorting techniques, check out How to Sort a List in Python to learn different sorting methods and their use cases.
  • The Time Complexity of Quick Sort is O(N Log N).
  • The Space Complexity of Quick Sort is O(Log N).
  • The Quick Sort Algorithm is the fastest than any other Sorting Algorithm.

Frequently Asked Questions:

1) Why is Quick Sort called “Quick”? 

Quick Sort is called “Quick” because it is very fast in most practical situations. It divides the list into smaller parts and sorts them efficiently, which usually results in better performance than many other sorting algorithms.

2) What happens if the pivot is chosen poorly? 

If the pivot divides the list unevenly, Quick Sort becomes slow. This can happen when the input list is already sorted, and the first or last element is chosen as the pivot.

3) Is Quick Sort recursive or iterative?

Quick Sort is naturally recursive, but it can also be implemented iteratively using a stack. Both approaches follow the same logic; the difference is how the sublists are managed.