How to sort three variables using at most two swaps?

后端 未结 10 1505
终归单人心
终归单人心 2020-12-10 00:56

The following algorithm can sort three variables x, y and z of type K which are comparable using operator<

10条回答
  •  既然无缘
    2020-12-10 01:40

    void sort(int& a, int& b, int& c)
    {
       swap(a, min(a, min(b, c)));
       swap(b, min(b, c));
    }
    

    2 swaps, 3 comparisons.

提交回复
热议问题