gpt4 book ai didi

java - Java如何根据元素值获取数组的索引

转载 作者:行者123 更新时间:2023-12-02 02:53:49 26 4
gpt4 key购买 nike

我有一个充满 double 值的数组。我想获取数组中第二个、第三个和第四个最低值的索引。这是我尝试过的,但我还没有得到我想要的。

double[] wantedVals = new double [3];
for(double n :allValues){
if(n < wantedVals[2] && n > wantedVals[1]) {
wantedVals[2] = n;
}
}
System.out.println("All Values: "+ Arrays.toString(allValues));
System.out.println("2nd, 3rd, 4th lowest values index: " + Arrays.toString(wantedVals));

}

这是输出。

All Values: [314.8490027477457, 558.1219589782775, 0.0, 538.3207360335937, 519.5707513178547, 271.85862019623363, 452.44377672120766, 448.3506884613316, 365.0024775172766, 380.61611237571117, 225.73376879634114, 310.28009020077326, 121.53621181051349, 95.45317487517113, 280.453364828718, 57.11775118122211, 343.1257001358977, 365.58868943629807, 530.7625668260243, 227.4473840254049, 319.9578951791938, 291.8377585984206, 494.999842171692, 464.97103404405743]
2nd, 3rd, 4th lowest values: [0.0, 0.0, 0.0]

我想要做的是获取所有值数组中第二个、第三个和第四个最低值的索引。

最佳答案

进行索引排序,然后输出索引。像这样:

final int MAX_ARRAY_SIZE = (the biggest that your all values array will be)
int index[] = new int[MAX_ARRAY_SIZE];
for(int i = 0; i < allValues.length(); i++)
{
index[ i ] = i;
}
//Simple Bubble Sort
for(int i = 0; i < allValues.length() - 1; i++)
{
for(int j = i + 1; j < allValues.length(); j++)
{
if(allValues[ index[ i ] ] > allValues[ index[ j ] ])
{
int temp = index[ i ];
index[ i ] = index[ j ];
index[ j ] = temp;
}
}
}
System.out.println("Indexes of 2nd to 4th lowest numbers are the following: ");
for(int i = 1; i < 4; i++)
{
System.out.println(index[ i ]);
}

如果它回答了您的问题,请将其标记为答案。

希望这有帮助!

关于java - Java如何根据元素值获取数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43403378/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com