sort c++ array
To sort a C++ array, you can use the std::sort() function from the
- Include the necessary header files:
#include <algorithm>
- Declare and initialize your array:
int arr[] = {5, 2, 8, 1, 9};
int size = sizeof(arr) / sizeof(arr[0]);
- Use the std::sort() function to sort the array:
std::sort(arr, arr + size);
The std::sort() function takes two parameters: the starting address of the array (arr) and the ending address of the array (arr + size). This will sort the elements of the array in ascending order.
- If you want to sort the array in descending order, you can use the std::greater<> comparator function as a third parameter to std::sort():
std::sort(arr, arr + size, std::greater<>());
This will sort the elements of the array in descending order.
That's it! Your array is now sorted. You can access the sorted elements using the array indices arr[0], arr[1], ..., arr[size-1].