开发者

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

开发者 https://www.devze.com 2023-03-01 08:53 出处:网络
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 t

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

精彩评论

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