quicksort
quicksort
Courses
Tutorials
DSA
Data Science
Web Tech
Sign In
DSA
Binary Search
Merge Sort
Quick Sort
Calculate Power
Karatsuba Algorithm
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a
pivot and partitions the given array around the picked pivot by placing the pivot in its correct
position in the sorted array.
Table of Content
QuickSort works on the principle of divide and conquer, breaking down the problem into
smaller sub-problems.
1. Choose a Pivot: Select an element from the array as the pivot. The choice of pivot
can vary (e.g., first element, last element, random element, or median).
2. Partition the Array: Rearrange the array around the pivot. After partitioning, all
elements smaller than the pivot will be on its left, and all elements greater than the
pivot will be on its right. The pivot is then in its correct position, and we obtain the
index of the pivot.
3. Recursively Call: Recursively apply the same process to the two partitioned sub-
arrays (left and right of the pivot).
4. Base Case: The recursion stops when there is only one element left in the sub-array,
as a single element is already sorted.
Always pick the first (or last) element as a pivot. The below implementation picks the
last element as pivot. The problem with this approach is it ends up in the worst case
when array is already sorted.
Pick a random element as a pivot. This is a preferred approach because it does not
have a pattern for which the worst case happens.
Pick the median element is pivot. This is an ideal approach in terms of time
complexity as we can find median in linear time and the partition function will always
divide the input array into two halves. But it takes more time on average as median
finding has high constants.
Partition Algorithm
The key process in quickSort is a partition(). There are three common algorithms to
partition. All these algorithms have O(n) time complexity.
1. Naive Partition: Here we create copy of the array. First put all smaller elements and
then all greater. Finally we copy the temporary array back to original array. This
requires O(n) extra space.
2. Lomuto Partition: We have used this partition in this article. This is a simple
algorithm, we keep track of index of smaller elements and keep swapping. We have
used it here in this article because of its simplicity.
3. Hoare’s Partition: This is the fastest of all. Here we traverse array from both sides
and keep swapping greater element on left with smaller on right while the array is
not partitioned. Please refer Hoare’s vs Lomuto for details.
The logic is simple, we start from the leftmost element and keep track of the index of smaller
(or equal) elements as i . While traversing, if we find a smaller element, we swap the current
element with arr[i]. Otherwise, we ignore the current element.
Let us understand the working of partition algorithm with the help of the following example:
1/6
In the previous step, we looked at how the partitioning process rearranges the array based
on the chosen pivot. Next, we apply the same method recursively to the smaller sub-arrays
on the left and right of the pivot. Each time, we select new pivots and partition the arrays
again. This process continues until only one element is left, which is always sorted. Once
every element is in its correct position, the entire array is sorted.
Below image illustrates, how the recursive method calls for the smaller sub-arrays on
the left and right of the pivot:
Quick Sort is a crucial algorithm in the industry, but there are other sorting algorithms that
may be more optimal in different cases.
C++CJavaPythonC#JavaScriptPHP
// Partition function
let i = low - 1;
i++;
swap(arr, i, j);
swap(arr, i + 1, high);
return i + 1;
// Swap function
function swap(arr, i, j)
arr[i] = arr[j];
arr[j] = temp;
quickSort(arr, pi + 1, high);
let n = arr.length;
quickSort(arr, 0, n - 1);
Output
Sorted Array
1 5 7 8 9 10
Time Complexity:
Best Case: (Ω(n log n)), Occurs when the pivot element divides the array into two
equal halves.
Average Case (θ(n log n)), On average, the pivot divides the array into two parts, but
not necessarily equal.
Worst Case: (O(n²)), Occurs when the smallest or largest element is always chosen as
the pivot (e.g., sorted arrays).
Please refer Time and Space Complexity Analysis of Quick Sort for more details.
It is Cache Friendly as we work on the same array to sort and do not copy data to any
auxiliary array.
Fastest general purpose algorithm for large data when stability is not required.
It is tail recursive and hence all the tail call optimization can be done.
It has a worst-case time complexity of O(n2), which occurs when the pivot is chosen
poorly.
It is not a stable sort, meaning that if two elements have the same key, their relative
order will not be preserved in the sorted output in case of quick sort, because here
we are swapping elements according to the pivot’s position (without considering
their original positions).
Efficient for sorting large datasets with O(n log n) average-case time complexity.
Used in partitioning problems like finding the kth smallest element or dividing arrays
by pivot.
Comment
More info
Advertise with us
Next Article
Similar Reads
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a
pivot and partitions the given array around the picked pivot by placing the pivot in its correct
position in the sorted array. Table of Content How does QuickSort Algorithm work? Working
of Partition Algorith
13 min read
The time complexity of Quick Sort is O(n log n) on average case, but can become O(n^2) in
the worst-case. The space complexity of Quick Sort in the best case is O(log n), while in the
worst-case scenario, it becomes O(n) due to unbalanced partitioning causing a skewed
recursion tree that requires a
4 min read
Quicksort: Quick sort is a Divide Conquer algorithm and the fastest sorting algorithm. In
quick sort, it creates two empty arrays to hold elements less than the pivot element and the
element greater than the pivot element and then recursively sort the sub-arrays. There are
many versions of Quicksort
2 min read
Iterative QuickSort
Visualization of QuickSort
Partitions in QuickSort
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar
Pradesh, 201305
Advertise with us
Company
About Us
Legal
Privacy Policy
In Media
Contact Us
Advertise with us
GeeksforGeeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
Tutorials Archive
DSA
Data Structures
Algorithms
DSA Roadmap
Top 100 DSA Interview Problems
Machine Learning
ML Maths
Data Visualisation
Pandas
NumPy
NLP
Deep Learning
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
Bootstrap
Web Design
Python Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Django
Computer Science
Operating Systems
Computer Network
Software Engineering
Engineering Maths
Software Development
Software Testing
DevOps
Git
Linux
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
System Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
Inteview Preparation
Competitive Programming
Company-Wise Preparation
Aptitude Preparation
Puzzles
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
World GK
GeeksforGeeks Videos
DSA
Python
Java
C++
Web Development
Data Science
CS Subjects