How to get lowest 3 elements in an int array

Matt9Atkins picture Matt9Atkins · Dec 2, 2012 · Viewed 10.1k times · Source

Hi I want to get the lowest 3 elements of an array. By lowest I mean the minimum value. I cannot use the collections.Sort method as I need to know the index of the elements. Therefore I am using the following code to get the lowest, but I need to know how I can get the lowest 3.

int minimum = grades[1];
int index = 1;

for(i=1; i<= numberOfStudents; i++){
    if (grades[i]<minimum){
        minimum = grades[i];
        index = i;
    }
}

Answer

Phil K picture Phil K · Dec 2, 2012

Here is a really simple way of doing it:

public static void main(String[] args) {
    int[] myArray = { 5, 8, 12, 9, 50, 11, 4 };

    System.out.println(Arrays.toString(myArray));
    System.out.println(Arrays.toString(getThreeLowest(myArray)));
}

private static int[] getThreeLowest(int[] array) {
    int[] lowestValues = new int[3];
    Arrays.fill(lowestValues, Integer.MAX_VALUE);

    for(int n : array) {
        if(n < lowestValues[2]) {
            lowestValues[2] = n;
            Arrays.sort(lowestValues);
        }
    }
    return lowestValues;
}

This outputs:

[5, 8, 12, 9, 50, 11, 4]
[4, 5, 8]


The call to Arrays.sort is only done to the local array, not your main array. The reason it does this is just to simplify the comparison against n.