We have discussed qsort() in C. C++ STL provides a similar function sort that sorts a vector or array (items with random access). Below is a simple program to show working of sort().
Array after sorting using default sort is : 0 1 2 3 4 5 6 7 8 9
So by default, sort() sorts an array in ascending order.
How to sort in descending order?
sort() takes a third parameter that is used to specify the order in which elements are to be sorted. We can pass “greater()” function to sort in descending order. This function does comparison in a way that puts greater element before.
Array after sorting : 9 8 7 6 5 4 3 2 1 0
How to sort in particular order?
We can also write our own comparator function and pass it as a third parameter.
Intervals sorted by start time : [1,9] [2,4] [4,7] [6,8]
This article is contributed by Shubham Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- History of C++
- Remove minimum elements from the array such that 2*min becomes more than max
- What are Forward declarations in C++
- __builtin_inf() functions of GCC compiler
- Alternate XOR operations on sorted array
- Find k ordered pairs in array with minimum difference d
- Sort the Queue using Recursion
- Count pairs with given sum | Set 2
- Case-specific sorting of Strings in O(n) time and O(1) space
- Arrange N elements in circular fashion such that all elements are strictly less than sum of adjacent elements
- Structures in C++
- Sort an array of strings based on the frequency of good words in them
- Variables in C++
- Greatest contiguous sub-array of size K
- Find the longest string that can be made up of other strings from the array
Improved By : rahuku