Vector-Sort in C++ hackerrank solution

Problem statement:


You are given a vector of integers and you need to sort them in non-decreasing order.

      

Sample Input:

The input consists of two lines. The first line contains an integer N, representing the size of the vector.
The second line contains N space-separated integers, the elements of the vector.
5 9 2 7 5 1
      

Sample Output:

Print the sorted vector in a single line, separated by spaces.
1 2 5 7 9

Explanation:

In this example, we have a vector of size 5 with elements {9, 2, 7, 5, 1}. After sorting the vector in non-decreasing order, we get {1, 2, 5, 7, 9}.

      
  #include <iostream>
  #include <vector>
  #include <algorithm>
  
  using namespace std;
  
  int main() {
      int N;
      cin >> N;
  
      vector vec(N);
      for (int i = 0; i < N; i++) {
          cin >> vec[i];
      }
  
      sort(vec.begin(), vec.end());
  
      for (int i = 0; i < N; i++) {
          cout << vec[i] << " ";
      }
  
      return 0;
  }
  

Code Explanation


We include the necessary header files, including for input/output operations, for using vectors, and for the sort() function.

In the main() function, we read the size of the vector (N) using cin.

We create a vector vec of size N to store the elements.

We iterate N times using a for loop and read each element of the vector using cin and store it in the corresponding index of the vector.

After reading all the elements, we use the sort() function to sort the vector in non-decreasing order. We pass the iterators vec.begin() and vec.end() as arguments to sort the entire vector.

Finally, we iterate over the sorted vector using a for loop and print each element followed by a space.

The solution demonstrates the usage of vectors, input handling, sorting, and output formatting in C++.

I hope this solution meets your requirements and provides a clear understanding of the problem and its solution!