开发者

How do I get the index of the smallest element in a double array?

How do I get the index of the s开发者_运维技巧mallest element in a double array,double[], in Java ?


You iterate over the array, comparing the different elements, always storing the value and index of the smallest one for comparison and retrieval.


shorter to give you the code.

public int minIndex(double... ds) {
    int idx = -1;
    double d= Double.POSITIVE_INFINITY;
    for(int i = 0; i < ds.length; i++)
        if(ds[i] < d) {
            d = ds[i];
            idx = i;
        }
    return idx;
}


Hold the lowest value seen so far, and the index of that value.

Look through the array, and if the value at that point is lower then use that value as the lowest from now on, and update the index held.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜