Sort in C++ Standard Template Library (STL)
Last Updated :
11 Jan, 2025
Sorting is one of the most basic operations applied to data. It means arranging the data in a particular order, which can be increasing, decreasing or any other order. In this article, we will discuss various ways of sorting in C++.
C++ provides a built-in function in C++ STL called sort() as the part of <algorithm> library for sorting the containers such as arrays, vectors, deque, etc.
sort(first, last, comp);
where,
- first: The beginning of the range to be sorted.
- last: The end of the range to be sorted.
- comp (optional): A custom comparison function to define sorting order. By default, it is ascending order.
Let's take a look at an example that sorts the given vector in ascending order:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {5, 3, 1, 4, 2};
// Default ascending order
sort(v.begin(), v.end());
for (int i : v) cout << i << " ";
return 0;
}
The sort() function implements the introsort sorting algorithm which is a combination of insertion sort, quick sort and heap sort. It automatically determines which algorithm to use according to the dataset.
Sorting data is a common operation in programming.
Other Sorting Algorithms in C++
Unfortunately, C++ does not provide implementation of any other sorting algorithm than Introsort and we can also not instruct to execute a particular algorithm to sort method. So, if we need a different sorting algorithm such as counting sort, we have to implement it by ourselves.
Bubble Sort Algorithm
Bubble Sort is a comparison-based sorting algorithm. It works by repeatedly swapping adjacent elements if they are in the wrong order, placing one element to its correct position in each iteration. Let's take a look at its implementation:
C++
#include <bits/stdc++.h>
using namespace std;
// Implementation of bubble sort algorithm
void bubbleSort(vector<int>& v) {
int n = v.size();
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (v[j] > v[j + 1]) {
// Swap element if in wrong order
swap(v[j], v[j + 1]);
}
}
}
}
int main() {
vector<int> v = {5, 3, 1, 4, 2};
// Use Bubble Sort to sort vector v
bubbleSort(v);
for (int i : v) cout << i << " ";
return 0;
}
Counting Sort Algorithm
Counting Sort is a non-comparison-based sorting algorithm. It works by counting the frequency of each distinct element in the input and use that information to place the elements in their correct sorted positions. Let's take a look at its implementation:
C++
#include <bits/stdc++.h>
using namespace std;
// Implementation of counting sort algorithm
void countingSort(vector<int>& v) {
int m = *max_element(v.begin(), v.end());
vector<int> count(m + 1, 0);
for (int i : v) {
count[i]++;
}
int index = 0;
for (int i = 0; i <= m; i++) {
while (count[i] > 0) {
v[index++] = i;
count[i]--;
}
}
}
int main() {
vector<int> v = {5, 3, 1, 4, 2};
// Use Counting Sort to sort vector v
countingSort(v);
for (int i : v) cout << i << " ";
return 0;
}
In a similar way, we can implement any sorting algorithm of our choice and need.
Common Sorting Problems in C++
As told earlier, sorting is one of the frequently used operations on data. It is used in solving a lot of programming problems. The below examples demonstrate the use of sort() in different problems:
Remove Duplicates in a Vector
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = { 1, 3, 1, 1, 2, 3, 2, 4, 5 };
// Sort the vector to bring duplicate elements adjacent
sort(v.begin(), v.end());
// Use unique() to bring all the duplicates to end
auto it = unique(v.begin(), v.end());
// Remove the duplicates
v.erase(it, v.end());
for (auto& i : v) cout << i << " ";
return 0;
}
Find the Kth Largest Element in an Array
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[5] = {5, 3, 1, 4, 2};
int n = sizeof(arr)/sizeof(arr[0]);
int k = 3;
// Sort the vector
sort(arr, arr + n);
// 3rd largest element will be present at 3 - 1 index
cout << arr[k - 1];
return 0;
}
Find the Pair with the Minimum Difference
C++
#include <bits/stdc++.h>
using namespace std;
pair<int, int> findMinDiff(vector<int>& v) {
// Sort the vector
sort(v.begin(), v.end());
// Initialize variables to track the minimum difference and the pair
int minDiff = INT_MAX;
pair<int, int> res;
// Traverse the vector to find the minimum difference
for (auto i = 0; i < v.size() - 1; i++) {
int diff = v[i + 1] - v[i];
if (diff < minDiff) {
minDiff = diff;
res = {v[i], v[i + 1]};
}
}
return res;
}
int main() {
vector<int> v = {4, 2, 9, 7, 1, 5};
// Find the pair with the minimum difference
pair<int, int> res = findMinDiff(v);
cout << res.first << ", " << res.second;
return 0;
}
Similar Reads
C++ Programming Language
C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Object Oriented Programming in C++
Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
10 min read
Vector in C++ STL
C++ vector is a dynamic array that stores collection of elements same type in contiguous memory. It has the ability to resize itself automatically when an element is inserted or deleted.Create a VectorBefore creating a vector, we must know that a vector is defined as the std::vector class template i
7 min read
Templates in C++
C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.For example, same sorting algorithm can work for different type, so
9 min read
30 OOPs Interview Questions and Answers [2025 Updated]
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is
15 min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning.In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot
8 min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. We will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program.C++ ClassesA class is a user-defined data type, which holds its own data members and
9 min read
C++ Polymorphism
The word polymorphism means having many forms. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So, the same person exhibits different behaviour in different situations. This is ca
5 min read
Virtual Function in C++
A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object a
6 min read