Tags
c++
Asked 1 years ago
25 Apr 2023
Views 264
kord

kord posted

How to sort array in C++ ?

Could you please provide information on how to sort an array in C++?
Mitul Dabhi

Mitul Dabhi
answered May 1 '23 00:00

To sort an array in C++, you can use the sort() function , which is defined in the <algorithm> header. The syntax of the sort() function is:



sort(start_address, end_address);

where start_address is the memory address of the first element of the array, and end_address is the memory address of the element one past the last element of the array.

For example, let's say we have an array arr of integers with n elements that we want to sort in ascending order. We can use the sort() function like this:



#include <algorithm>
using namespace std;

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

    sort(arr, arr + n);

    // print the sorted array
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    return 0;
}

This code will sort the arr array in ascending order using the sort() function, and then print the sorted array. The output will be: 1 2 3 4 5.

By default, the sort() function sorts the array in ascending order . However, you can specify a custom sorting order by passing a comparator function as a third argument to the sort() function.
Post Answer