Reputation: 371
I have an array filled with double values. I want to get the index of the 2nd and the 3rd and 4th lowest values in the array. This is what I have tried but I haven't been getting what I want.
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));
}
Here is the output.
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]
What I want to do is get the indexes of the 2nd, 3rd and 4th lowest values in All Values array.
Upvotes: 0
Views: 205
Reputation: 145
Do an index sort, and then output the indexes. Like this:
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 ]);
}
Mark this as the answer if it answers your question.
Hope this helps!
Upvotes: 1
Reputation: 1962
I can think of two ways to accomplish this: sort the array, and search it repetitively. Neither of these is likely to be the most efficient, but they should be good enough for most use cases (with the latter being slightly more efficient).
If you want to sort the array, simple use Arrays.paralellSort() and get whatever values you need from the resulting array.
If you want to search it repetitively, then simply go through the array and find the lowest value. Make note of this value in a variable, and repeat the original code -- unless the current value is the lowest. It would be best to use a HashSet to contain the list of already selected values, since a HashSet can efficiently be checked for a value and have a value added to it.
Upvotes: 1