Last Updated : 23 Jul, 2025
Sort a vector in ascending order means arranging the elements of vector in such a way that the first element will be smallest, second element will be second smallest and so on. In this article, we will learn different ways to sort the vector in ascending order in C++.
The most efficient way to sort the vector in ascending order is by using sort() method. Let’s take a look at a simple example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 4, 3, 2, 5};
// Sort the vector
sort(v.begin(), v.end());
for (auto i : v)
cout << i << " ";
return 0;
}
There are also some other methods in C++ by which we can sort the vector in ascending order. Some of them are as follows:
Using stable_sort()The stable_sort() method is similar to sort() method with the only difference being that the stable_sort() maintains the order of elements if the elements are equal.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 4, 3, 2, 5};
// Sort vector in ascending order
stable_sort(v.begin(), v.end());
for (auto i : v)
cout << i << " ";
return 0;
}
Explanation: Here we sort the vector in ascending order using stable_sort() method which maintains the order of elements.
Using MultisetMultiset is an ordered container that stores the data in the given sorted order. It can be used to sort vector by first pushing all the elements from vector to multiset and then putting them back one by one.
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> v = {1, 4, 3, 2, 5};
// Create multiset from v
multiset<int> ms(v.begin(), v.end());
// Copy back all the elements frmo ms to v
v.assign(ms.begin(), ms.end());
for (auto i : v)
cout << i << " ";
return 0;
}
Explanation: The multiset container stores elements in ascending order by default.
If you want to implement any other sorting algorithm such as bubble sort, counting sort, etc. you will have to implement them by yourself.
Using Bubble Sort AlgorithmBubble Sort is a simple sorting algorithm that repeatedly swap adjacent elements if they are in the wrong order. This process is repeated until the vector is sorted.
C++
#include <bits/stdc++.h>
using namespace std;
// Bubble sort implementation
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(v[j], v[j + 1]);
}
}
}
int main() {
vector<int> v = {1, 4, 3, 2, 5};
// Sort v usign bubble sort
bubbleSort(v);
for (auto i : v)
cout << i << " ";
return 0;
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4