-2

This is a program to simply return the min value and the number of time it occurs in the array. If the array is filled with {13, 28, 5, 11} it returns the min as 5 and the count as 1. However, When the array is filled with the given numbers it returns the count as 2, when it should be 1. How would I fix this? Thankyou

public class Test4{
   public static void main(String[] args){
      int[] array = {4, 20, 30, 4, 25, 25, 6, 2, 29, 27, 1, 29, 11, 6, 10, 17, 8};
      findMin(array);
   }

   public static void findMin(int[] array) {
      if (array == null || array.length < 1)
         return;
      int count = 0;
      int min = array[0];

      for (int i = 1; i <= array.length - 1; i++) {

         if (min > array[i]) {
            min = array[i];  
            if(min == array[i]){

               count++;
            }
         }
      }
      System.out.println("The minimum is: " + min +"\n" + "The count is: " + count);
   }
}
Julia Dune
  • 19
  • 3

1 Answers1

3

You should initialize the count to 1 and reset is to 1 whenever the current min value is changed:

  int count = 1; // initial count should be 1
  int min = array[0];

  for (int i = 1; i <= array.length - 1; i++) {
     if (min > array[i]) {
        // new minimum - reset count to 1
        min = array[i];
        count = 1;
     } else if (min == array[i]) {
         // same minimum - increment count
         count++;
     }
  }
Eran
  • 387,369
  • 54
  • 702
  • 768