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++ Standard Template Library (STL)
The C++ Standard Template Library (STL) is a set of template classes and functions that provides the implementation of common data structures and algorithms such as lists, stacks, arrays, sorting, searching, etc. It also provides the iterators and functors which makes it easier to work with algorith
9 min read
is_standard_layout template in C++
The std::is_standard_layout template of C++ STL is used to check whether the type is a standard layout or not. It returns a boolean value showing the same. Syntax: template < class T > struct is_standard_layout; Parameters: This template contains single parameter T (Trait class) to check wheth
3 min read
is_scalar template in C++
The std::is_scalar template of C++ STL is used to check whether the given type is a scalar type or not. It returns a boolean value showing the same. Syntax: template < class T > struct is_scalar; Parameter: This template accepts a single parameter T (Trait class) to check whether T is a scalar
2 min read
std is_object Template in C++
The std::is_object template of C++ STL is used to check whether the given type is object or not. It returns a boolean value showing the same. Syntax: template <class T > struct is_object; Parameter: This template accepts a single parameter T (Trait class) to check whether T is a object type or
2 min read
std::list::sort in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::sort() sort() function is used to sort the
2 min read
<numeric> library in C++ STL
Common mathematical functions std::fabs: This function returns the absolute value. std::sqrt: This function returns the square root std::sin: This function returns the sine measured in radians. Special mathematical functions std::beta: This function evaluates the (complete) Beta integral with given
2 min read
Partial Template Specialization in C++
In C++, template specialization enables us to define specialized versions of templates for some specific argument patterns. It is of two types: Full Template SpecializationPartial Template SpecializationIn this article, we will discuss the partial template specialization in C++ and how it is differe
3 min read
is_class template in C++
The std::is_class template of C++ STL is used to check whether the given type is class or not. It returns a boolean value showing the same. Syntax: template <class T> struct is_class; Parameter: This template accepts single parameter T (Trait class) to check whether T is a class or not. Return
2 min read
std::forward_list::sort() in C++ STL
Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of
3 min read
Difference Between STL and Standard Library in C++
In C++, the term "Standard Library" and "Standard Template Library" are often misinterpreted as the same. Although they sound same with only a single word difference, they refer to the different part of the C++ programming language. In this article, we will learn what's the difference between the C+
3 min read