Shiv_k Shiv_k - 4 years ago 83
Java Question

Why the output is 0 for a[0] instead of -1?

I am new to java array, I would like to calculate small element in an array when array contains negative elements.

class test_array {
//test_array class
public static void main(String args[]) {
int[] a = {4, 2, 99, 9, -1, 0};
int small = a[0];

for (int i = 1; i < a.length; i++) {
if(a[i]<small) {
a[0]=a[i];
a[i]=small;
}
}

System.out.println(a[0]);
}
}

Answer Source
int small = a[0];

here you gave 4 to small

you didn't change this value if you find a smaller one. Instead of that you are changing smaller one into this value by

a[i] = small;

this code and small value doesn't change at all. Your 'small' value is always 4.

when it compares a[5] and small (it means 0 and 4) it passes if statement and makes a[0]=a[5] ( gives it '0').

You are comparing only with first char of array with this algoryhtm but you need to compare it with a dynamic "small" value. Change code like that.

class test_array {
//test_array class  

    public static void main(String args[])
    {
            int[] a={4,2,99,9,-1,0};           
            int small=a[0];

        for (int i=1;i<a.length;i++)               
        {                                      
            if(a[i]<small)
            {                                             
                small=a[i];
            } 
        }

        System.out.println(small);       
    }   
}       

Choose first array element as small, then compare. If there is any smaller value, give this value to 'small'. Do it in a loop for all array and find smallest value.

Bonus: Btw it's good to work on simple algorythms like that for starting but know that for hard times there is easier way to sort arrays and find min and max values like

Arrays.sort(arr);

It will sort all array. Then arr[0] will be min and arr[arr.lenght-1] will be max values.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download