Open In App

How to Sort an Array in C++?

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, an array is a sequential data storage container that stores data of the same type. In this article, we will learn how to sort an array in C++.

Example:

Input:
myArray ={5,4,1,2,3}

Output:
Sorted Array: 1 2 3 4 5

Sorting an Array in C++

To sort an array in C++, we can simply use the std::sort() method provided by the STL, which takes two parameters, the first one points to the array where the sorting needs to begin, and the second parameter is the length up to which we want to sort the array.

The default sorting order is ascending order but we can also provide the custom comparator to sort in different order as the third parameter.

Syntax of std::sort()

Use the below syntax to sort an array in C++.

sort(arr, arr+n)

Here,

  • arr is the name of the array which also acts as a pointer to the first element of the array.
  • n is the size of the array.

C++ Program to Sort an Array

The following program illustrates how we can sort an array in C++ using the std::sort() method.

C++
// C++ Program to how to sort an array
#include <algorithm>
#include <iostream>
using namespace std;

int main()
{
    // Initializing an array
    int arr[] = { 5, 4, 1, 2, 3 };

    // Calculate the size of the array
    int n = sizeof(arr) / sizeof(arr[0]);

    // Print the array before sorting the elements
    cout << "Array Before Sorting: ";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;

    // Sort the array
    sort(arr, arr + n);

    // Print the array after sorting the elements
    cout << "Array After Sorting: ";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

Output
Array Before Sorting: 5 4 1 2 3 
Array After Sorting: 1 2 3 4 5 

Time Complexity: O(N log N), where N is the size of the array.
Auxiliary Space: O(1)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads