sort() in C++ STL
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().
Output :// C++ program to demonstrate default behaviour of // sort() in STL. #include <bits/stdc++.h> using namespace std; int main() { int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0}; int n = sizeof (arr)/ sizeof (arr[0]); sort(arr, arr+n); cout << "\nArray after sorting using " "default sort is : \n" ; for ( int i = 0; i < n; ++i) cout << arr[i] << " " ; return 0; } |
Array after sorting using default sort is : 0 1 2 3 4 5 6 7 8 9So 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 increasing order. This function does comparison in a way that puts greater element before.
// C++ program to demonstrate descending order sort using // greater<>(). #include <bits/stdc++.h> using namespace std; int main() { int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0}; int n = sizeof (arr)/ sizeof (arr[0]); sort(arr, arr+n, greater< int >()); cout << "Array after sorting : \n" ; for ( int i = 0; i < n; ++i) cout << arr[i] << " " ; return 0; } |
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.
// A C++ program to demonstrate STL sort() using // our own comparator #include<bits/stdc++.h> using namespace std; // An interval has start time and end time struct Interval { int start, end; }; // Compares two intervals according to staring times. bool compareInterval(Interval i1, Interval i2) { return (i1.start < i2.start); } int main() { Interval arr[] = { {6,8}, {1,9}, {2,4}, {4,7} }; int n = sizeof (arr)/ sizeof (arr[0]); // sort the intervals in increasing order of // start time sort(arr, arr+n, compareInterval); cout << "Intervals sorted by start time : \n" ; for ( int i=0; i<n; i++) cout << "[" << arr[i].start << "," << arr[i].end << "] " ; return 0; } |
Intervals sorted by start time :
[1,9] [2,4] [4,7] [6,8]
No comments:
Post a Comment