-2

I know how to find the largest and smallest elements of a Java:

  1. sort the array
  2. use a for loop to iterate over the array and check for the smallest.

But is there a way to check for the largest or smallest in one statement? Also, order needs to be preserved.

Conditions:

  1. No method calls in the same class
  2. Sequence is unsorted, and remains unsorted
  3. No access to external libraries (i.e. ArrayUtils is not allowed).

Assume that this is a plain Java array, i.e. int[], not ArrayList<T> or LinkedList<T>.

3
  • 2
    If it's naturally sorted, largest and smallest are first/last or last/first elements (depending on the sort order), why the loop!? Commented Nov 16, 2013 at 13:45
  • Oh sorry, it is unsorted (I put unordered in the title, but meant unsorted). Commented Nov 16, 2013 at 13:46
  • @user473973 what RC meant: If you sort the array in step 1, you don't have to loop because the smallest element is then the first element of the array - that's what sorting usually does! Commented Nov 16, 2013 at 13:51

1 Answer 1

2
Integer arr[] = new Integer[50];
// fill the array with integers
Collections.min(Arrays.asList(arr));
Collections.max(Arrays.asList(arr));

Example:

Integer arr[] = {7, 8, 1, 2, 6};
System.out.println(Collections.min(Arrays.asList(arr)));
System.out.println(Collections.max(Arrays.asList(arr)));

Output:

1
8

If you must use int[] instead of Integer[] with the one statement constraint as proposed, you can make use of ArrayUtils.toObject function which will convert the int[] to it's corresponding wrapper class Integer[]. But i don't think you are after using external library though.

Sign up to request clarification or add additional context in comments.

3 Comments

Slightly cheating, but as asList() wrapps the array it is probably allowed. For performance direct array access will be faster, so be aware of huge arrays.
this won't work with int[] however
yup, but OP requires the operation in one statement. Here it is, in one statement ;) :P

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.