Most efficient way to find smallest of 3 numbers Java?

后端 未结 17 2238
故里飘歌
故里飘歌 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:08

    For those who find this topic much later:

    If you have just three values to compare there is no significant difference. But if you have to find min of, say, thirty or sixty values, "min" could be easier for anyone to read in the code next year:

    int smallest;
    
    smallest = min(a1, a2);
    smallest = min(smallest, a3);
    smallest = min(smallest, a4);
    ...
    smallest = min(smallest, a37);
    

    But if you think of speed, maybe better way would be to put values into list, and then find min of that:

    List mySet = Arrays.asList(a1, a2, a3, ..., a37);
    
    int smallest = Collections.min(mySet);
    

    Would you agree?

提交回复
热议问题