Finding the minimum value of int numbers in an array (Java)

后端 未结 10 1978
天涯浪人
天涯浪人 2020-12-22 10:42

I\'m trying to find the minimum value of numbers in an array but it doesn\'t always work out properly. This is the code I wrote:

        for (int i=0; i <         


        
10条回答
  •  庸人自扰
    2020-12-22 11:26

    There's no need for the outer loop, it only runs once and you don't use i anyway. why do you have it?

    For the inner loop, you need to compare against the minimum value. Right now you are comparing it against the first element in the array, which is not necessarily the minimum value.

    min = arr[0];
    for (j=0; j < arr.length; j++) {
        if (arr[j] < min) {  //<---fix is here
            min = arr[j];
        }
    }
    

    Also you could start the loop at 1, since you don't need to compare arr[0] against itself (it was just assigned to min)

提交回复
热议问题