Most efficient way to find smallest of 3 numbers Java?

后端 未结 17 2279
故里飘歌
故里飘歌 2020-12-14 05:44

I have an algorithm written in Java that I would like to make more efficient. A part that I think could be made more efficient is finding the smallest of 3 numbers. Currentl

17条回答
  •  半阙折子戏
    2020-12-14 06:15

    I would use min/max (and not worry otherwise) ... however, here is another "long hand" approach which may or may not be easier for some people to understand. (I would not expect it to be faster or slower than the code in the post.)

    int smallest;
    if (a < b) {
      if (a > c) {
        smallest = c;
      } else { // a <= c
        smallest = a;
      }
    } else { // a >= b
      if (b > c) {
        smallest = c;
      } else { // b <= c
        smallest = b;
      }
    }
    

    Just throwing it into the mix.

    Note that this is just the side-effecting variant of Abhishek's answer.

提交回复
热议问题