Fastest way of finding the middle value of a triple?

前端 未结 25 951
庸人自扰
庸人自扰 2020-12-04 12:20

Given is an array of three numeric values and I\'d like to know the middle value of the three.

The question is, what is the fastest way of finding the midd

25条回答
  •  日久生厌
    2020-12-04 12:40

    The easiest way is through sorting. For example consider this code :

    import java.util.Arrays;
    
    
    int[] x = {3,9,2};
    Arrays.sort(x); //this will sort the array in ascending order 
    
    //so now array x will be x = {2,3,9};
    //now our middle value is in the middle of the array.just get the value of index 1
    //Which is the middle index of the array.
    
    int middleValue = x[x.length/2]; // 3/2 = will be 1
    

    That's it.It's that much simple.

    In this way you don't need to consider the size of the array.So if you have like 47 different values then you can also use this code to find the middle value.

提交回复
热议问题