How to Sort Vector in Ascending Order in C++?
Last Updated :
05 Feb, 2024
In C++, vectors are sequence containers that can change their size automatically during runtime. In this article, we will discuss how to sort the elements of a vector in ascending order in C++.
Example
Input:
myVector = { 5,2,4,1,9,33,8,10}
Output:
myVector = { 1, 2, 4, 5, 8, 9, 10, 33 }
Sort a Vector in Ascending Order in C++
In C++, we can easily and efficiently sort the elements of the vector using the std::sort() method provided by the algorithm library of STL. We have to provide the iterator to the start and end of the vector. By default, this function sorts dataset in the ascending order but we can change it by providing a custom comparator.
C++ Program to Sort a Vector in Ascending Order
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector< int > myVector = {5, 2, 4, 1, 9, 33, 8, 10};
cout << "Unsorted Vector: " ;
for ( int num : myVector) {
cout << num << " " ;
}
cout << endl;
sort(myVector.begin(), myVector.end());
cout << "Sorted Vector in Ascending Order: " ;
for ( int num : myVector) {
cout << num << " " ;
}
cout << endl;
return 0;
}
|
Output
Unsorted Vector: 5 2 4 1 9 33 8 10
Sorted Vector in Ascending Order: 1 2 4 5 8 9 10 33
Time Complexity: O(N log N) where N is the number of elements present in the vector
Auxilary Space: O(log N)
Share your thoughts in the comments
Please Login to comment...