4

I want to find out the minimum and maximum value in an array of integers.

Which one of the following ways would be the more efficient?

  1. Sort the array and then look at start and end to get the minimum and maximum.

  2. Convert the array into a list using Arrays.asList() and then use the Collections.min() method.

The code where I want to use this is the following:

// Find missing number from an array of consecutive numbers arranged randomly
import java.util.Arrays;

public class MissingNumber {

    public static void main(String[] args) {

        int[] consecutiveRandomNos = { 3, 6, 5 };

        System.out.println(addNumbers(consecutiveRandomNos));
        System.out.println("The missing number is "
                        + (returnSum(consecutiveRandomNos) - addNumbers(consecutiveRandomNos)));
    }

    public static int addNumbers(int... numbers) {
        int result = 0;

        for (int number : numbers) {
            result += number;
        }

        return result;
    }

    public static int returnSum(int... nos) {

        Arrays.sort(nos);

        int max = nos[nos.length - 1];

        int min = nos[0];

        int total = 0;

        for (int i = min; i <= max; i++) {
            total += i;
        }

        return total;
    }
}
3
  • write some code first Commented Mar 19, 2015 at 14:42
  • Probably number 2 :D Commented Mar 19, 2015 at 14:44
  • thanks all for your quick reply. I was thinking which would be a better way . I should have posted the code first. Commented Mar 19, 2015 at 18:39

3 Answers 3

8

Sort is O(Nlog(N)) at best. You can find min and max trivially in O(n) just iterating over the array.

int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for(int i=0; i<array.length; i++)
{
    if(array[i] < min)
       min = array[i]
    if(array[i] > max)
       max = array[i]
}

Edit:


I noticed you pasted some extra code and that you actually want to find a missing number in an array of consecutive numbers. Rather than iterating all that much, there are mathematical summations that can help you here in O(1). In fact, you can solve the entire problem with a single for loop:

int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int sum = 0;
for(int i=0; i<array.length; i++)
{
    if(array[i] < min)
       min = array[i];
    if(array[i] > max)
       max = array[i];
    sum += array[i];
}

return (max - min + 1)(max + min)/2 - sum;
Sign up to request clarification or add additional context in comments.

7 Comments

Note, this is the same as other answers, but finds both max AND min in one pass. Hell people at stackoverflow are fast!
That the iteration inside Collections#min is basically doing the same thing (with iterators), so basically those answers are equally valid. Turns out 3 answers were submitted basically within 30 seconds of one another (I didn't get to see them), so they might seem repetitive.
could save an evaluation, instead of using two ifs, use an else. You also needn't worry about the edge case array[i] == max because the effect is the same. It's trivial, but could add up
Mmm, I could use an 'else if' if that is what you mean. I cannot remove the second if altogether since most new items I see might well be < max.
Just wanted to note, I've noticed you we're indexing from the array 4 times in your first code, and I'm a bit of a performaphobe... wouldn't it be faster to initialize a temp variable to update with the current value during iteration?? That way you only index the array once per iteration and test/update with the variable instead of the index.
|
4

sorting costs O(NlogN), going through an array to find min and max costs O(N). No need for convertsion to list, just iterrate the array.

Comments

0

Collection#min source code:

585     public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
586         Iterator<? extends T> i = coll.iterator();
587         T candidate = i.next();
588 
589         while (i.hasNext()) {
590             T next = i.next();
591             if (next.compareTo(candidate) < 0)
592                 candidate = next;
593         }
594         return candidate;
595     }

It's O(n) in terms of time complexity. If your sorting algorithm is O(n) (post it please), they're both the same, again, in terms of time complexity.

7 Comments

"If your sorting algorithm is O(n)" probably not, or? :D
@Trinimon Depends, the OP might be Chuck Norris.
@Trinimon Usually, it cannot have this complexity but dependending on the constraints on the data, it can. For example, if you want to sort an array of numbers in [0; 100], it is possible to do it in O(n).
@ArnaudDenoyelle That's the best case.. but note that there exist algorithms that cannot have O(n) even if the data is sorted.
@Arnaud Denoyelle: I know, there are some algorithms that need only O(N) for already sorted lists. However, I assumed equal distribution, because there were no special note on this. Only Chuck Norris needs always O(n) :D (p.s. check en.wikipedia.org/wiki/Sorting_algorithm)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.