How to sort three variables using at most two swaps?

后端 未结 10 1504
终归单人心
终归单人心 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 02:00

    Find the smallest, this takes 2 comparisons, and swap it into the first position. Then compare the remaining 2 and swap if necessary.

    if (x < y) {
       if (z < x) swap(x,z);
    } else {
      if (y < z) swap(x,y);
      else swap(x,z);
    } 
    if(z

    This takes 3 comparisons, but only two swaps.

提交回复
热议问题