Sort is sorted in the STL library, and sometimes the O (n^2) algorithm that bubbles, chooses, and so on times out, we can use the Quick sort O (n log n) in the STL to do the sorting
Sort in the <algorithm> library, the prototype is as follows:
| 1234 |
template<class RandomAccessIterator> void sort ( RandomAccessIterator first, RandomAccessIterator last );template <class RandomAccessIterator, class Compare> voidsort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp ); |
He has two forms, one with three parameters and one with two parameters, let's talk about two parameters first!
The first two parameters of sort are the start address and the abort address
such as: Sort (a,a+n) for a[0] a[1] a[2] ... a[n-1] Sort
The code is as follows:
| 1234567891011 |
#include <algorithm>#include <cstdio>usingnamespacestd;intmain() { intn,a[1001]; scanf("%d",&n); //输入有多少个数 for(inti = 1;i <= n;i++) scanf("%d",&a[i]); //输入这个数列 sort(a+1,a+n+1); //对a[1] a[2] a[3] ... a[n] 排序 for(inti = 1;i <= n;i++) printf("%d",a[i]); //输出 return0‘} |
This is the default ascending, what if it is descending?
So, we're going to use the third argument, and the third argument is a comparison function
| 123 |
boolcmp(int a,int b) { returna > b;} |
This is the comparison function in descending order, meaning:
is true for a > B, does not swap, a < b is false, the interchange
Then we call sort (a+1,a+n+1,cmp), we can sort on a[1] a[2] a[3] ... a[n].
Sort can also be ordered for structs, such as:
| 123456789101112131415161718 |
#include <algorithm>#include <cstdio>usingnamespacestd;structNode { intx,y;}p[1001];intn;intcmp(Node a,Node b) { if(a.x != b.x) returna.x < b.x; //如果a.x不等于b.x,就按x从小到大排 returna.y < b.y; //如果x相等按y从小到大排}intmain() { scanf("%d",&n); for(inti = 1;i <= n;i++) scanf("%d%d",&p[i].x,&p[i].y); sort(p+1,p+n+1,cmp); for(inti = 1;i <= n;i++) scanf("%d %d\n",p[i].x,p[i].y); return0;} |
The above code means, if a.x is not equal to b.x, press X from small to large row; if x equals y from small to large
Structs can also overload operators so that sort can be sorted by its own rules with only two parameters, such as:
| 12345678910111213141516171819202122 |
#include <algorithm>#include <cstdio>usingnamespacestd;structNode { intx,y; booloperator < (Node cmp) const{ if(a.x != cmp.x) returna.x < cmp.x; returna.y < cmp.y; }}p[1001];intn;//int cmp(Node a,Node b) {// if (a.x != b.x) return a.x < b.x; //如果a.x不等于b.x,就按x从小到大排// return a.y < b.y; //如果x相等按y从小到大排//}intmain() { scanf("%d",&n); for(int i = 1;i <= n;i++) scanf("%d%d",&p[i].x,&p[i].y); sort(p+1,p+n+1); for(inti = 1;i <= n;i++) scanf("%d %d\n",p[i].x,p[i].y); return0;} |
Sort in the STL library is the sorting function