-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>.

user473973
  • 711
  • 2
  • 13
  • 23
  • 2
    If it's naturally sorted, largest and smallest are first/last or last/first elements (depending on the sort order), why the loop!? –  Nov 16 '13 at 13:45
  • Oh sorry, it is unsorted (I put unordered in the title, but meant unsorted). – user473973 Nov 16 '13 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! – isnot2bad Nov 16 '13 at 13:51

1 Answers1

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.

Sage
  • 15,290
  • 3
  • 33
  • 38
  • 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. – Maarten Bodewes Nov 16 '13 at 13:55
  • this won't work with `int[]` however –  Nov 16 '13 at 13:57
  • yup, but OP requires the operation in one statement. Here it is, in one statement ;) :P – Sage Nov 16 '13 at 13:57