
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort an Array Using std::sort in C++
Sorting of an array refer to the process of arranging the elements of the array in ascending or descending order. In this article, we will learn how to use the std::sort function from the C++ STL library to sort an array.
In this problem, you are given an array of integers, and you need to arrange the elements in ascending order using std::sort. For example:
// Input array int arr[] = {5, 2, 9, 1, 5, 6}; // Output {1, 2, 5, 5, 6, 9} // Explanation: The array is sorted in ascending order.
C++ std::sort Function
The std::sort function is a part of the C++ Standard Template Library (STL) that is defined in the algorithm header file. It is used to sort a range of elements (not just arrays) in ascending or descending order. The syntax of the std::sort function is as follows:
// sort in ascending order std::sort(arr, arr + n); // sort in descending order std::sort(arr, arr + n, std::greater<datatype>());
Where, arr is the pointer to the first element of the array, n is the size of the array, and std::greater<datatype>() is an optional parameter that is used to specify the sorting order (ascending or descending). If you do not provide this parameter, the array will be sorted in ascending order by default.
Note: The std:: prefix is used to indicate that the function is part of the C++ Standard Library. You can also use using namespace std; at the beginning of your code to avoid writing std:: before every STL function.
Sorting an Array Using std::sort
The code below shows how to use the std::sort function to sort an array of integers in ascending order and then in descending order:
#include <iostream> #include <algorithm> int main(){ int arr[] = {5, 2, 9, 1, 5, 6}; // Calculate the size of the array int n = sizeof(arr) / sizeof(arr[0]); // Sort in ascending order std::sort(arr, arr + n); std::cout << "Array in ascending order: "; for (int i = 0; i < n; ++i) { std::cout << arr[i] << " "; } std::cout << std::endl; // Sort in descending order std::sort(arr, arr + n, std::greater<int>()); std::cout << "Array in descending order: "; for (int i = 0; i < n; ++i) { std::cout << arr[i] << " "; } std::cout << std::endl; return 0; }
The output of the above code will be:
Array in ascending order: 1 2 5 5 6 9 Array in descending order: 9 6 5 5 2 1
Time and Space Complexity
Time Complexity: O(n log n), where n is the number of elements in the array. In the backend, std::sort uses quick sort algorithm.
Space Complexity: O(n), to store array of n elements