Implement Quicksort with first element as pivot
Last Updated :
23 Jul, 2025
QuickSort is a Divide and Conquer algorithm. It picks an element as a pivot and partitions the given array around the pivot. There are many different versions of quickSort that pick the pivot in different ways.
- Always pick the first element as a pivot.
- Always pick the last element as a pivot.
- Pick a random element as a pivot.
- Pick the median as the pivot.
Note: Here we will be implementing quick sort by picking the first element as the pivot.
Quick Sort by picking the first element as the Pivot:
The key function in quick sort is a partition. The target of partitions is to put the pivot in its correct position if the array is sorted and the smaller (or equal) to its left and higher elements to its right and do all this in linear time.
Partition Algorithm:
There can be many ways to do partition, the following pseudo-code adopts the method given in the CLRS book.
- 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 (or equal) element, we swap the current element with arr[i].
- Otherwise, we ignore the current element.
Pseudo Code for recursive QuickSort function:
// low –> Starting index, high –> Ending index
quickSort(arr[], low, high) {
if (low < high) {
// pi is partitioning index, arr[pi] is now at right place
pi = partition(arr, low, high);
quickSort(arr, low, pi – 1); // Before pi
quickSort(arr, pi + 1, high); // After pi
}
}
Pseudo code for partition() function
/* This function takes first element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than or equal to pivot) to left of pivot and all greater elements to right of pivot */
partition (arr[], low, high) {
// first element as pivot
pivot = arr[low]
k = high
for (i = high; i > low; i--) {
if (arr[i] > pivot){
swap arr[i] and arr[k];
k--;
}
}
swap arr[k] and arr[low]
return k;
}
Illustration of partition() :
Consider: arr[] = { 7, 6, 10, 5, 9, 2, 1, 15, 7 }
First Partition: low = 0, high = 8, pivot = arr[low] = 7
Initialize index of right most element k = high = 8.
- Traverse from i = high to low:
- if arr[i] is greater than pivot:
- Swap arr[i] and arr[k].
- Decrement k;
- At the end swap arr[low] and arr[k].
Now the correct position of pivot is index 5
First partitionSecond Partition: low = 0, high = 4, pivot = arr[low] = 2
Similarly initialize k = high = 4;
The correct position of 2 becomes index 1. And the left part is only one element and the right part has {6, 5, 7}.
Partition of the left halfOn the other hand partition happens on the segment [6, 8] i.e., the array {10, 9, 15}.
Here low = 6, high = 8, pivot = 10 and k = 8.
The correct position of 10 becomes index 7 and the right and left part both has only one element.
Partition of the right halfThird partition: Here partition the segment {6, 5, 7}. The low = 2, high = 4, pivot = 6 and k = 4.
If the same process is applied, we get correct position of 6 as index 3 and the left and the right part is having only one element.
Third partitionThe total array becomes sorted in this way. Check the below image for the recursion tree
Recursion tree for partitions
Follow the below steps to implement the approach.
- Use a recursive function (say quickSort) to initialize the function.
- Call the partition function to partition the array and inside the partition function do the following
- Take the first element as pivot and initialize and iterator k = high.
- Iterate in a for loop from i = high to low+1:
- If arr[i] is greater than pivot then swap arr[i] and arr[k] and decrement k.
- After the iteration is swap the pivot with arr[k].
- Return k-1 as the point of partition.
- Now recursively call quickSort for the left half and right half of the partition index.
Implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
/*This function takes first element as pivot, the function
places the pivot element(first element) on its sorted
position and all the element lesser than pivot will placed
left to it, and all the element greater than pivot placed
right to it.*/
int partition(int arr[], int low, int high)
{
// First element as pivot
int pivot = arr[low];
int k = high;
for (int i = high; i > low; i--) {
if (arr[i] > pivot)
swap(arr[i], arr[k--]);
}
swap(arr[low], arr[k]);
// As we got pivot element index is end
// now pivot element is at its sorted position
// return pivot element index (end)
return k;
}
/* The main function that implements QuickSort
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quickSort(int arr[], int low, int high)
{
// If low is lesser than high
if (low < high) {
// idx is index of pivot element which is at its
// sorted position
int idx = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, idx - 1);
quickSort(arr, idx + 1, high);
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver Code
int main()
{
int arr[] = { 7, 6, 10, 5, 9, 2, 1, 15, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
cout << "Sorted array: \n";
printArray(arr, n);
return 0;
}
// This Code is contributed by Harsh Raghav
C
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int low, int high) {
int pivot = arr[low]; // Choosing the pivot element
int start = low;
int end = high;
int k = high;
// Iterate from the end of the array to the start
for (int i = high; i > low; i--) {
// If the current element is greater than the pivot,
// swap it with the element at index k and decrement k
if (arr[i] > pivot)
swap(&arr[i], &arr[k--]);
}
// Swap the pivot element with the element at index k
swap(&arr[low], &arr[k]);
return k; // Return the index of the pivot element after partitioning
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
// Partition the array and get the index of the pivot element
int idx = partition(arr, low, high);
// Recursively sort the subarrays before and after the pivot element
quickSort(arr, low, idx - 1);
quickSort(arr, idx + 1, high);
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {7, 6, 10, 5, 9, 2, 1, 15, 7};
int n = sizeof(arr) / sizeof(arr[0]);
// Call quickSort to sort the array
quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
Java
import java.util.Arrays;
class QuickSort {
/* This function takes first element as pivot, the
function places the pivot element(first element) on its
sorted position and all the element lesser than pivot
will placed left to it, and all the element greater than
pivot placed right to it.*/
int partition(int arr[], int low, int high)
{
// First element as pivot
int pivot = arr[low];
int st = low; // st points to the starting of array
int end
= high; // end points to the ending of the array
int k = high;
for (int i = high; i > low; i--) {
if (arr[i] > pivot)
swap(arr, i, k--);
}
swap(arr, low, k);
// As we got pivot element index is end
// now pivot element is at its sorted position
// return pivot element index (end)
return k;
}
// Function to swap two elements
public static void swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/* The main function that implements QuickSort
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quickSort(int arr[], int low, int high)
{
// If low is lesser than high
if (low < high) {
// idx is index of pivot element which is at its
// sorted position
int idx = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, idx - 1);
quickSort(arr, idx + 1, high);
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver Code
public static void main(String args[])
{
int arr[] = { 7, 6, 10, 5, 9, 2, 1, 15, 7 };
int n = arr.length;
QuickSort ob = new QuickSort();
ob.quickSort(arr, 0, n - 1);
System.out.println("Sorted array");
ob.printArray(arr, n);
}
}
Python
# This function takes first element as pivot, the function
# places the pivot element(first element) on its sorted
# position and all the element lesser than pivot will placed
# left to it, and all the element greater than pivot placed
# right to it.
def partition(array, low, high):
# First Element as pivot
pivot = array[low]
# st points to the starting of array
start = low + 1
# end points to the ending of the array
end = high
while True:
# It indicates we have already moved all the elements to their correct side of the pivot
while start <= end and array[end] >= pivot:
end = end - 1
# Opposite process
while start <= end and array[start] <= pivot:
start = start + 1
# Case in which we will exit the loop
if start <= end:
array[start], array[end] = array[end], array[start]
# The loop continues
else:
# We exit out of the loop
break
array[low], array[end] = array[end], array[low]
# As we got pivot element index is end
# now pivot element is at its sorted position
# return pivot element index (end)
return end
# The main function that implements QuickSort
# arr[] --> Array to be sorted,
# low --> Starting index,
# high --> Ending index
def quick_sort(array, start, end):
# If low is lesser than high
if start < end:
# idx is index of pivot element which is at its
# sorted position
idx = partition(array, start, end)
# Separately sort elements before
# partition and after partition
quick_sort(array, start, idx-1)
quick_sort(array, idx+1, end)
# Function to print an array
def print_arr(arr, n):
for i in range(n):
print(arr[i], end=" ")
print()
# Driver Code
arr1 = [7, 6, 10, 5, 9, 2, 1, 15, 7]
quick_sort(arr1, 0, len(arr1)-1)
print_arr(arr1, len(arr1))
# This code is contributed by Aditya Sharma
C#
using System;
class QuickSort
{
/* This function takes first element as pivot, the
function places the pivot element(first element) on its
sorted position and all the element lesser than pivot
will placed left to it, and all the element greater than
pivot placed right to it.*/
int partition(int[] arr, int low, int high)
{
// First element as pivot
int pivot = arr[low];
int st = low; // st points to the starting of array
int end = high; // end points to the ending of the array
int k = high;
for (int i = high; i > low; i--)
{
if (arr[i] > pivot)
{
swap(arr, i, k--);
}
}
swap(arr, low, k);
// As we got pivot element index is end
// now pivot element is at its sorted position
// return pivot element index (end)
return k;
}
// Function to swap two elements
public static void swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/* The main function that implements QuickSort
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quickSort(int[] arr, int low, int high)
{
// If low is lesser than high
if (low < high)
{
// idx is index of pivot element which is at its
// sorted position
int idx = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, idx - 1);
quickSort(arr, idx + 1, high);
}
}
/* Function to print an array */
void printArray(int[] arr, int size)
{
int i;
for (i = 0; i < size; i++)
Console.Write(arr[i] + " ");
Console.WriteLine();
}
// Driver Code
public static void Main()
{
int[] arr = { 7, 6, 10, 5, 9, 2, 1, 15, 7 };
int n = arr.Length;
QuickSort ob = new QuickSort();
ob.quickSort(arr, 0, n - 1);
Console.WriteLine("Sorted array");
ob.printArray(arr, n);
}
}
JavaScript
function partition(function partition(array, low, high) {
// First Element as pivot
let pivot = array[low];
// st points to the starting of array
let start = low + 1;
// end points to the ending of the array
let end = high;
while (true) {
// It indicates we have already moved all the elements to their correct side of the pivot
while (start <= end && array[end] >= pivot) {
end--;
}
// Opposite process
while (start <= end && array[start] <= pivot) {
start++;
}
// Case in which we will exit the loop
if (start <= end) {
[array[start], array[end]] = [array[end], array[start]];
// The loop continues
} else {
// We exit out of the loop
break;
}
}
[array[low], array[end]] = [array[end], array[low]];
// As we got pivot element index is end
// now pivot element is at its sorted position
// return pivot element index (end)
return end;
}
function quick_sort(array, start, end) {
// If low is lesser than high
if (start < end) {
// idx is index of pivot element which is at its
// sorted position
let idx = partition(array, start, end);
// Separately sort elements before
// partition and after partition
quick_sort(array, start, idx - 1);
quick_sort(array, idx + 1, end);
}
}
function print_arr(arr) {
console.log(arr.join(" "));
}
// Driver Code
let arr1 = [7, 6, 10, 5, 9, 2, 1, 15, 7];
quick_sort(arr1, 0, arr1.length - 1);
console.log("Sorted array: ");
print_arr(arr1);
//contributed by Aditya Sharma
OutputSorted array:
1 2 5 6 7 7 9 10 15
Complexity Analysis:
- Time Complexity:
- Average Case: O(N * logN), where N is the length of the array.
- Best Case: O(N * logN)
- Worst Case: O(N2)
- Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem