关于快速排序及重载<号的问题(Strict Weak Ordering 部分暂时难以理解)

 1 #include<iostream>
 2 #include<algorithm>
 3 using namespace std;
 4 int n,a[1005];
 5 void qsort(int l,int r)
 6 {
 7     int x=a[(l+r)/2];
 8     int i=l,j=r;
 9     while (i<j) 
10     {
11         while (a[i]<x) 
12         {
13 //          cout<<i<<' '<<a[i]<<'\n';
14             i++;
15         }
16         while (a[j]>x) j--;
17         if (i<=j)
18         {
19             int t=a[i];
20             a[i]=a[j];
21             a[j]=t;
22             i++;
23             j--;    
24         }
25     }
26     if (l<j) qsort(l,j);
27     if (r>i) qsort(i,r);
28 }
29 int main()
30 {
31     cin>>n;
32     for (int i=1;i<=n;i++) cin>>a[i];
33     qsort(1,n);
34     for (int i=1;i<=n;i++) cout<<a[i]<<' ';
35 }

 

第11行与第16行的代码中<不能为<=;因为这样i就会一直遍历+下去,程序错误。同理
struct node { int x,y; bool operator <(node a) const { return min(x,a.y)<min(y,a.x);//不能写<= }
 
高深理解

简单来说,\rm STLSTL 的任何比较函数(包括但不限于使用std::sort、std::lower_bound、std::priority_queue时重载的小于号),都需要满足以下四个条件:(用 << 表示重载的运算符)

  1. x\not<xx?<x (非自反性)
  2. 若 x<yx<y,则 y\not<xy?<x (非对称性)
  3. 若 x<y,y<zx<y,y<z,则 x<zx<z (传递性)
  4. 若 x\not<y,y\not<x,y\not<z,z\not<yx?<y,y?<x,y?<z,z?<y,则 x\not<z,z\not<xx?<z,z?<x (不可比性的传递性)
posted @ 2019-12-08 12:42  Fiora·master  阅读(50)  评论(0)    收藏  举报