Search code examples
javaarraysindexingminimum

Am I referencing or instancing wrong for finding the index of the smallest value in an array?


My array is:

int a = new int[] {20,20,30,40,6,70,80}

My code for finding minimum value is correct, but when I try to put

idx=i

or

idx= i+1

and return idx, my output is 0.

int minval=0;
int idx=0;
if(a==null || a.length==0) {
    return null;
}
else if(a.length!=0) {  
    for(int i=0; i<a.length-1; i++) {
        if(a[i]<a[i+1]) {
            a[i+1]=a[i];
            minval=a[i];
        }
        else
            minval= a[i+1];
        }
        return minval;
    }
    return null;
}

Solution

  • You should be comparing each element with the current minimum value instead of the adjacent value.

    int minIdx = 0;
    for(int i = 1; i < a.length; i++) {
        if(a[i] < a[minIdx]) minIdx = i;
    }
    return minIdx; //minIdx is index of smallest value; a[minIdx] is the smallest value