Chewy
Chewy

Reputation: 85

Finding min element in an array

Testing out code to find the min and max element in an array. My code for finding the maximum works fine .. but my min prints "Minimum element in the array: 0". I probably have one little mistake that is throwing me off lol.

 public void deleteMin() {

  // set value for comparision starting from the beginning of the array
  int arrayMin = arr[0];

  for (int j = 0; j < nElems; j++) {
     if (arr[j] < arrayMin) {
        arrayMin = arr[j];
     }
    // insert delete functionality    
  } 
  System.out.println("Minimum element in the array: " + arrayMin);
}

Upvotes: 0

Views: 1959

Answers (3)

gran_profaci
gran_profaci

Reputation: 8473

If you're just iterating over the array, then utilize the fact that you can have two pointers going instead of just the one.

Hence, this can get the job done with half the number of iterations :

public static int minElementInArray(int[] a) {      
    int minArrayElement = Integer.MAX_VALUE;

    for (int i = 0; i < a.length / 2; i++) {
        if (a[i] < minArrayElement) {
            minArrayElement = a[i];
        } 

        if (a[a.length - i - 1] < minArrayElement) {
            minArrayElement = a[a.length - i - 1];
        }
    }       
    return minArrayElement;
}

Upvotes: 0

aioobe
aioobe

Reputation: 421310

Your code is correct as it stands now. The only reason for arrayMin to contain 0 after the code has finished is if

  • nElems was not set to arr.length, or
  • 0 was indeed the smallest element in the array.

The code could be simplified.

Java 8:

int arrayMin = IntStream.of(arr).min().getAsInt();

Java 7:

int arrayMin = arr[0];
for (int i : arr)
    arrayMin = Math.min(arrayMin, i);

(Note that both solutions assume a non-empty array since min would otherwise be undefined.)

Upvotes: 10

Jean-Fran&#231;ois Savard
Jean-Fran&#231;ois Savard

Reputation: 21004

You could do

List<Integer> yourList = new ArrayList<Integer>(arr.length);
for (int i= 0; i< arr.length; i++)
    yourList.add(arr[i]); 

Collections.min(yourList);
Collections.max(yourList);

See max and min documentation.

Or if you have Java 8 as @ioobe already mentionned :

IntStream.of(arr).min().getAsInt();

Upvotes: 1

Related Questions