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
- Sum of array Elements without using loops and recursion
- Minimum Increment / decrement to make array elements equal
- Program to Convert Hexadecimal to Octal
- Count elements such that there are exactly X elements with values greater than or equal to X
- Check whether it is possible to make both arrays equal by modifying a single element
- Get maximum items when other items of total cost of an item are free
- Sum of width (max and min diff) of all Subsequences
- Sorting array elements with set bits equal to K
- C++ Program to concatenate two strings using Operator Overloading
- Is there any equivalent to typedef of C/C++ in Java ?
- Rearrange an array to maximize i*arr[i]
- Count elements in a vector that match a target value or condition
- Swapping of subranges from different containers in C++
- Maximizing the elements with a[i+1] > a[i]
- Find K items with the lowest values
Improved By : rahuku