-4

I did a class earlier where we went through this kind of algorithm but can't find my code. How do I find the 2nd biggest number in an array with only 1 scan?

I was thinking about using nodes but that would screw up if the largest and 2nd largest one starts on same side. And an ugly way is to have two extra temp-variables and "find" the smaller one of them.

So anyone got any tip? Oh and it's java if you have the code. In the meantime I'll try to search more on google!

3
  • In real life: Arrays.sort(myArray); return myArray[myArray.length - 2]; Commented Aug 28, 2016 at 23:52
  • 3
    The two extra temp variables is fine... Commented Aug 28, 2016 at 23:56
  • I think I'll just use the two variables for now Commented Aug 28, 2016 at 23:58

1 Answer 1

0

This is the way I would go about getting the second highest number:

//      The array containing number.
        int[] number = {1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10};

//      The int[] is copied to Integer[] array. This is done because the Arrays class cannot sort primitives (such as int). If any other primitive type, they can be converted to their respective objects.
        Integer[] numberInteger = new Integer[number.length];

//      Populate the Integer[] with data from int[].
        for(int i = 0; i<number.length; i++)
        {
            numberInteger[i] = number[i];
        }

//      Sort the Integer[] array in reverse order.
        Arrays.sort(numberInteger, Collections.<Integer>reverseOrder());

//      Print the result out.
        System.out.println("The second highest number is: "+numberInteger[1]);

//      Output is~~~~~~~ The second highest number is: 9

If you have other primitive type (e.g. double[]) it can be copied to it's respective object (e.g Double[]).

P.S. If using Java 8, Integer[] array can be populated in an easier way. Streams can be used to populate Integer[].

//      Instead of using a for loop, Streams are used.
        Integer[] numberInteger = Arrays.stream(number).boxed().toArray(Integer[]::new);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.