how to sort array in c++ stockoverflow

To sort an array in C++, you can use the std::sort function from the <algorithm> library. Here are the steps to sort an array in C++:

  1. Include the necessary header file:
#include <algorithm>
  1. Declare and initialize the array:
int arr[] = {5, 2, 8, 1, 9};
int n = sizeof(arr) / sizeof(arr[0]);
  1. Use the std::sort function to sort the array:
std::sort(arr, arr + n);

The std::sort function takes two iterators as arguments: the beginning and the end of the range to be sorted. In this case, we pass arr (the beginning of the array) and arr + n (the end of the array).

  1. Print the sorted array:
for (int i = 0; i < n; i++) {
    std::cout << arr[i] << " ";
}

This loop iterates over the sorted array and prints each element.

The complete code looks like this:

#include <iostream>
#include <algorithm>

int main() {
    int arr[] = {5, 2, 8, 1, 9};
    int n = sizeof(arr) / sizeof(arr[0]);

    std::sort(arr, arr + n);

    for (int i = 0; i < n; i++) {
        std::cout << arr[i] << " ";
    }

    return 0;
}

When you run this code, it will output the sorted array: 1 2 5 8 9.

Let me know if you need further assistance!