0% found this document useful (0 votes)
18 views5 pages

Python Quicksort Algorithm Explained

The document provides a tutorial on the Quicksort algorithm using Python, explaining its efficiency as a fast sorting method. It details the process of selecting a pivot element, partitioning the array, and recursively sorting sub-arrays. Additionally, it includes a code implementation and discusses the time complexity of Quicksort, highlighting its average case performance of O(n log n).

Uploaded by

virajsawant0211
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views5 pages

Python Quicksort Algorithm Explained

The document provides a tutorial on the Quicksort algorithm using Python, explaining its efficiency as a fast sorting method. It details the process of selecting a pivot element, partitioning the array, and recursively sorting sub-arrays. Additionally, it includes a code implementation and discusses the time complexity of Quicksort, highlighting its average case performance of O(n log n).

Uploaded by

virajsawant0211
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1/3/26, 11:31 AM DSA Quicksort with Python


 Tutorials  References  Exercises  Certificates  Search... Upgrade Get Certified Sign In

HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C# BOOTSTRAP REACT MYS
Trees
Binary Trees
Binary Search Trees
AVL Trees
Graphs
Linear Search
Binary Search
Bubble Sort
Selection Sort
Insertion Sort
Quick Sort
Counting Sort
Radix Sort
Merge Sort
DSA Quicksort with Python
COLOR
❮ Previous Next ❯
Python MySQL PICKER
MySQL Get Started
MySQL Create Database
MySQL Create Table Quicksort
MySQL Insert
MySQL Select As the name suggests, Quicksort is one of the fastest sorting algorithms. 
The Quicksort algorithm takes an array of values, chooses one of the values as the 'pivot'

element, and moves the other values so that lower values are on the left of the pivot
element, and higher values are on the right of it.

Sort

In this tutorial the last element of the array is chosen to be the pivot element, but we could
also have chosen the first element of the array, or any element in the array really.

Then, the Quicksort algorithm does the same operation recursively on the sub-arrays to
the left and right side of the pivot element. This continues until the array is sorted.

Recursion is when a function calls itself.

After the Quicksort algorithm has put the pivot element in between a sub-array with lower
values on the left side, and a sub-array with higher values on the right side, the algorithm
calls itself twice, so that Quicksort runs again for the sub-array on the left side, and for the
sub-array on the right side. The Quicksort algorithm continues to call itself until the sub-
arrays are too small to be sorted.

The algorithm can be described like this:

[Link] 1/5
1/3/26, 11:31 AM DSA Quicksort with Python


 Tutorials  References  Exercises  Certificates  Upgrade Get Certified Sign In

How it works:
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C# BOOTSTRAP REACT MYS
Trees
1. Choose a value in the array to be the pivot element.
Binary Trees 2. Order the rest of the array so that lower values than the pivot element are on the left,
Binary Search Trees and higher values are on the right.
AVL Trees 3. Swap the pivot element with the first element of the higher values so that the pivot
Graphs element lands in between the lower and higher values.
Linear Search 4. Do the same operations (recursively) for the sub-arrays on the left and right side of
Binary Search the pivot element.
Bubble Sort
Selection Sort
Insertion Sort
Quick Sort
Counting Sort
Manual Run Through
Radix Sort
Merge Sort Before we implement the Quicksort algorithm in a programming language, let's manually
run through a short array, just to get the idea.
Python MySQL
Step 1: We start with an unsorted array.
MySQL Get Started
MySQL Create Database
[ 11, 9, 12, 7, 3]
MySQL Create Table
MySQL Insert
MySQL Select
Step 2: We choose the last value 3 as the pivot element.

[ 11, 9, 12, 7, 3]

Step 3: The rest of the values in the array are all greater than 3, and must be on the right
side of 3. Swap 3 with 11.

[ 3, 9, 12, 7, 11]

Step 4: Value 3 is now in the correct position. We need to sort the values to the right of 3.
We choose the last value 11 as the new pivot element.

[ 3, 9, 12, 7, 11]

Step 5: The value 7 must be to the left of pivot value 11, and 12 must be to the right of it.
Move 7 and 12.

[ 3, 9, 7, 12, 11]

Step 6: Swap 11 with 12 so that lower values 9 and 7 are on the left side of 11, and 12 is
on the right side.

[ 3, 9, 7, 11, 12]

Step 7: 11 and 12 are in the correct positions. We choose 7 as the pivot element in sub-
array [ 9, 7], to the left of 11.

[ 3, 9, 7, 11, 12]

[Link] 2/5
1/3/26, 11:31 AM DSA Quicksort with Python


 Tutorials  ReferencesStep
 8:Exercises
We must swapCertificates
9 with 7.  Upgrade Get Certified Sign In

HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C# BOOTSTRAP REACT MYS
[ 3, 7, 9, 11, 12]
Trees
Binary Trees
And now, the array is sorted.
Binary Search Trees
AVL Trees
Graphs Run the simulation below to see the steps above animated:
Linear Search
Binary Search
Bubble Sort Sort
Selection Sort
Insertion Sort [ 11, 9, 12, 7, 3 ]
Quick Sort
Counting Sort
Radix Sort

Implement Quicksort in Python


Merge Sort

Python MySQL
To write a 'quickSort' method that splits the array into shorter and shorter sub-arrays we
MySQL Get Started
use recursion. This means that the 'quickSort' method must call itself with the new sub-
MySQL Create Database arrays to the left and right of the pivot element. Read more about recursion here.
MySQL Create Table
MySQL Insert To implement the Quicksort algorithm in a Python program, we need:
MySQL Select
1. An array with values to sort.
2. A quickSort method that calls itself (recursion) if the sub-array has a size larger
than 1.
3. A partition method that receives a sub-array, moves values around, swaps the
pivot element into the sub-array and returns the index where the next split in sub-
arrays happens.

The resulting code looks like this:

Example Get your own Python Server

Using the Quicksort algorithm in a Python program:

def partition(array, low, high):


pivot = array[high]
i = low - 1

for j in range(low, high):


if array[j] <= pivot:
i += 1
array[i], array[j] = array[j], array[i]

array[i+1], array[high] = array[high], array[i+1]


return i+1

def quicksort(array, low=0, high=None):


if high is None:
high = len(array) - 1

if low < high:


pivot_index = partition(array, low, high)
quicksort(array, low, pivot_index-1)
quicksort(array, pivot_index+1, high)

[Link] 3/5
1/3/26, 11:31 AM DSA Quicksort with Python
mylist = [64, 34, 25, 5, 22, 11, 90, 12] ❯
 Tutorials  References quicksort(mylist)
Exercises  Certificates  Upgrade Get Certified Sign In
print(mylist)
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C# BOOTSTRAP REACT MYS
Trees
Binary Trees Run Example »
Binary Search Trees
AVL Trees
Graphs
Linear Search
Binary Search
Quicksort Time Complexity
Bubble Sort The worst case scenario for Quicksort is O(n ). This is when the pivot element is either the
2

Selection Sort highest or lowest value in every sub-array, which leads to a lot of recursive calls. With our
Insertion Sort implementation above, this happens when the array is already sorted.
Quick Sort
Counting Sort But on average, the time complexity for Quicksort is actually just O(n log n), which is a lot
Radix Sort better than for the previous sorting algorithms we have looked at. That is why Quicksort is
Merge Sort so popular.

Below you can see the significant improvement in time complexity for Quicksort in an
Python MySQL
average scenario O(n log n), compared to the previous sorting algorithms Bubble,
MySQL Get Started Selection and Insertion Sort with time complexity O(n ): 2

MySQL Create Database


MySQL Create Table
MySQL Insert
MySQL Select

The recursion part of the Quicksort algorithm is actually a reason why the average sorting
scenario is so fast, because for good picks of the pivot element, the array will be split in
half somewhat evenly each time the algorithm calls itself. So the number of recursive calls
do not double, even if the number of values n double.

❮ Previous Sign in to track progress Next ❯

-->
 PLUS SPACES GET CERTIFIED FOR TEACHERS

[Link] 4/5
1/3/26, 11:31 AM DSA Quicksort with Python


 Tutorials  References 
FOR BUSINESS
Exercises 
CONTACT US
Certificates  Upgrade Get Certified Sign In

HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C# BOOTSTRAP REACT MYS
Trees
Binary Trees Top Tutorials Top References
Binary Search Trees
HTML Tutorial HTML Reference
AVL Trees CSS Tutorial CSS Reference
JavaScript Tutorial JavaScript Reference
Graphs How To Tutorial SQL Reference
Linear Search SQL Tutorial Python Reference
Python Tutorial [Link] Reference
Binary Search [Link] Tutorial Bootstrap Reference
Bootstrap Tutorial PHP Reference
Bubble Sort PHP Tutorial HTML Colors
Java Tutorial Java Reference
Selection Sort
C++ Tutorial AngularJS Reference
Insertion Sort jQuery Tutorial jQuery Reference

Quick Sort Top Examples Get Certified


Counting Sort HTML Examples HTML Certificate
Radix Sort CSS Examples CSS Certificate
JavaScript Examples JavaScript Certificate
Merge Sort How To Examples Front End Certificate
SQL Examples SQL Certificate
Python Examples Python Certificate
Python MySQL [Link] Examples
Bootstrap Examples
PHP Certificate
jQuery Certificate
MySQL Get Started PHP Examples Java Certificate
Java Examples C++ Certificate
MySQL Create Database XML Examples C# Certificate
jQuery Examples XML Certificate
MySQL Create Table
MySQL Insert
MySQL Select
     FORUM ABOUT ACADEMY
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by [Link].

[Link] 5/5

Common questions

Powered by AI

Both Quicksort and Merge Sort have an average time complexity of O(n log n), but they differ in performance based on specific conditions. Quicksort is often faster in practice due to its in-place sorting and smaller constant factors, making it cache-friendly . Merge Sort is more stable and has a guaranteed O(n log n) time complexity, even in its worst-case scenario. Merge Sort’s stability and consistent performance make it preferable when dealing with large datasets that require stable sorting .

Quicksort offers an average time complexity of O(n log n) which is significantly more efficient than Bubble Sort, Selection Sort, and Insertion Sort, all of which have average time complexities of O(n²). This makes Quicksort particularly advantageous for large datasets. Its divide-and-conquer approach allows for efficient recursion and partitioning, often resulting in faster execution compared to the more linear approach of the other algorithms .

The partitioning process in Quicksort involves choosing a pivot element and rearranging the array such that all elements less than the pivot are on its left, and all elements greater are on the right . This is done by swapping elements around the pivot and continuing until the pivot is in its correct position. Partitioning is crucial as it enables the recursive breakdown of the array into smaller sub-arrays, which are subsequently sorted, effectively dividing the problem into simpler parts .

Recursion in the Quicksort algorithm allows the method to call itself to sort sub-arrays, contributing to the sorting process by progressively breaking down larger arrays into smaller, manageable parts . After placing the pivot in its correct position, Quicksort recursively sorts the left and right sub-arrays around the pivot, continuing this process until the sub-arrays are of size one or zero, which results in the sorted sequence .

The choice of pivot is critical in Quicksort because a poor pivot selection leads to unbalanced partitions and degrades performance to its worst-case time complexity of O(n²). Optimal strategies for selecting a pivot include choosing the median, using the "median of three" method (comparing first, middle, last elements), or selecting a random element, all of which aim to produce more balanced partitions and thereby enhance the overall efficiency of the sort .

To optimize Quicksort for sorted arrays and prevent performance degradation, techniques such as randomized pivot selection or the "median-of-three" strategy can be implemented to ensure that the pivot choice is neither the maximum nor minimum consistently . Additionally, incorporating hybrid approaches like SwiftSort, which switches to Insertion Sort for small sub-arrays, can improve efficiency as small arrays benefit from the simplicity of Insertion Sort . These strategies reduce the likelihood of encountering the worst-case scenario and enhance overall algorithm performance.

The Quicksort algorithm selects the pivot element based on the implementation, commonly choosing the last element, the first element, or a random element from the array . The choice of pivot significantly affects the algorithm's efficiency because it influences how evenly the array is partitioned. An ideal pivot splits the array into two equal halves, maintaining an average time complexity of O(n log n). If the pivot is always the highest or lowest element in a sorted array, the time complexity degrades to O(n²).

Quicksort reaches its worst-case time complexity of O(n²) when the pivot selections lead to highly unbalanced partitions, such as when the smallest or largest element is consistently chosen as the pivot in a sorted array . This can be mitigated by using a better pivot selection strategy, like choosing a random element, the median, or using the "median of three" method, which tends to create more balanced partitions, reducing the probability of hitting the worst-case scenario .

Understanding Quicksort’s recursive process of dividing a problem and then solving sub-problems with the same strategy enhances comprehension of similar recursive algorithms, such as Merge Sort and Divide and Conquer algorithms broadly . It demonstrates how to handle base cases, manage recursive calls and transitions, and how to combine results effectively. Mastery of these recursive structures is fundamental for implementing efficient algorithms across various applications in computing .

Being an in-place sorting algorithm means Quicksort uses a constant amount of additional space, specifically O(log n) space due to the recursion stack . This reduces the need for additional space allocations compared to algorithms that require additional arrays, such as Merge Sort with its O(n) space complexity. As a result, Quicksort is memory efficient, making it advantageous when dealing with memory-constrained environments .

You might also like