Open In App

How to Sort Vector in Ascending Order in C++?

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ Program to Sort a Vector in Ascending Order
  
#include <iostream>
#include <vector>
#include <algorithm>
  
using namespace std;
  
int main() {
    // Create a vector
    vector<int> myVector = {5, 2, 4, 1, 9, 33, 8, 10};
  
    // Print the unsorted vector
    cout << "Unsorted Vector: ";
    for (int num : myVector) {
        cout << num << " ";
    }
    cout << endl;
  
    // Sort the vector in ascending order using the sort function
    sort(myVector.begin(), myVector.end());
  
    // Print the sorted vector
    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)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads