开发者

Grabbing the next biggest number

I have this:

  int[] tal = {3, 8, 5, 8, 2, 3, 9, 12, 21};
  int max=tal[0];
  for(int i=0;i<tal.length;i++){
      if(tal[i]>5){
          max=开发者_运维技巧tal[i];
      }
  }
  System.out.println("Biggest: "+ max);

Im reading Java, how can i make print out the next biggest number


Assuming you don't want to sort the array, as some of the other answers suggest:

int[] tal = {3, 8, 5, 8, 2, 3, 9, 12, 21};
int max = tal[0];
int previous = Integer.MIN_VALUE;
for (int i = 1; i < tal.length; i++) {
    if (tal[i] > max) {
        previous = max;
        max = tal[i];
    }
    else if (tal[i] > previous) {
        previous = tal[i];
    }
}
System.out.println("Biggest: "+ max);
System.out.println("2nd Biggest: "+ previous);

Credits to @Andreas_D for the original code, which I modified to fix a problem.

There are some extra conditions you may need to check for; for example, the array needs to contain at least two elements for a valid result. Realistically, I would only opt for a solution such as this if you expect to be dealing with large inputs, and if you always need the second largest (or largest) number. Otherwise, just go with the Arrays.sort solution.

Because I'm mostly a .NET guy, I'll show you the Pex explorations of this implementation (Pex is a tool which looks for edge cases in your code): alt text http://subbot.net/personal/external/stackoverflow/pex-second-largest.png

Andreas contributed a modification, which changes the behavior when it comes to duplicate entries:

// Second if condition
else if ( tal[i] < max && tal[i] > previous) {
// ...

More Pex explorations after the modification:

Grabbing the next biggest number


That doesn't print out the greater number, it prints out the last number in tal greater than 5.

Assuming you actually want to print out the largest number and then the next largest number, your best bet is to sort the array using Arrays.sort, then you can access the largest and second largest elements.

Arrays.sort(tal);
System.out.println("Largest: " + tal[tal.length - 1]);
System.out.println("Second largest: " + tal[tal.length - 2]);

If you only want to deal with unique values, then you'll need to generate a list of unique values first, before sorting the array.


You'll need to keep track of two numbers a and b. The first two numbers in the list go into a and b.

Continue through the list. Each time you encounter a number x higher than min(a,b) and not equal to max(a,b), your a and b get the values max(a,b) and x. When you reach the end, and a!=b, your second largest number is min(a,b). If a==b, then there is no second largest number.

int[] tal = {3, 8, 5, 8, 2, 3, 9, 12, 21};
int a = Integer.MIN_VALUE;
int b = Integer.MIN_VALUE;
for(int x : tal) {
if(x > Math.min(a,b) && x!=Math.max(a,b)) {
        a = Math.max(a,b);
        b = x;
    }
}
if(a != b) {
    System.out.println("1st largest: "+Math.max(a,b));
    System.out.println("2nd largest: "+Math.min(a,b));
}


public class Main
{
    static int second_largest(int[] arr)
    {
        if(arr.length == 0)
        {
            return Integer.MIN_VALUE;
        }

        int maximum = arr[0];
        for(int i=1; i<arr.length; ++i)
        {
            maximum = Math.max(maximum, arr[i]);
        }

        int second = Integer.MIN_VALUE;
        for(int i=0; i<arr.length; ++i)
        {
            if(arr[i] < maximum)
            {
                second = Math.max(second, arr[i]);
            }
        }

        return second;
    }

    public static void main(String[] args)
    {
        int[] arr = {3,8,5,8,2,3,9,12,21};
        System.out.println(second_largest(arr));
    }
}


You can use Arrays.sort to sort the array, and then just grab the next-biggest number from the sorted array

Arrays.sort(tal);


The simple way is to use List instead of array. Firstly, you find the maximum. Then remove it and find the maximum againg in the new list. The beneficial is that you can go further and find the next big integer and so on.

But I agree with others, sorting is better here.


If you want the next max value to the provided value, below code would be useful

        int[] tal = {3, 8, 5, 8, 2, 3, 9, 12, 21};
        int currentMax = 8; //set your current value here
        int nextMax = 0;
        Arrays.sort(tal);
        for (int i = 0; i < tal.length; i++) {
            if (tal[i] > currentMax) {
                nextMax = tal[i];
                break;
            }
        }
        System.out.println("next max  is : " + nextMax);


Well for one, currently the biggest wont be printed properly if(tal[i]>5){ should be if(tal[i]> max) to find the 2nd largest, have something like int secondMax = tal[1] swap between max & secondMax if necessary..then iterate through the rest of the array. If a number is greater than secondMax swap and so on and so forth :-)


This will ensure that should there be two values in the array that is the maximum value (21 in this case) then it will not be returned as the second largest value as well.

int[] tal = {3, 8, 5, 8, 2, 3, 9, 12, 21, 21 };
Arrays.sort(tal);
int index = tal.length - 1;
int max = tal[index];
int nextMax = max;
index -= 1;
while (nextMax == max && index >= 0) {
    nextMax = tal[index];
    index -= 1;
}
if (index < 0) System.out.println("no other value available");
else System.out.println("Next max: " + nextMax);


If anyone who is okay with sorting, the following might help. In the below snippet, you can pick a int of your choice and you will get the next higher int value from the Array. Hope it might help someone.

public static void main(String args[]) {
    Integer[] tal = { 3, 8, 5, 8, 222, 3, 9, 222, 12, 21 };

    /* Array before the sorting */
    System.out.println("Before Sorting:");
    for (int counter : tal) {
        System.out.println(counter);
    }

    /* Sorting of array */
    Arrays.sort(tal);

    /* Array after sorting */
    System.out.println("\nAfter Sorting:");
    for (int counter : tal) {
        System.out.println(counter);
    }

    int selectedInt = 222;

    System.out.println("\n\nYou selected :: " + selectedInt);

    System.out.println("\nNext higher value for " + selectedInt + " in the Array is "
            + findNextHigherIntInArray(tal, selectedInt));

}

public static int findNextHigherIntInArray(Integer[] myArray, int selectedInt) {
    int someIntVar = 0;

    int max = Collections.max(Arrays.asList(myArray));

    for (int i = 0; i < myArray.length; i++) {

        if (myArray[i] > selectedInt) {
            someIntVar = myArray[i];
//                 System.out.println(myArray[i]);
                break;
            }
            // return selectedInt if it is the max 
            if (selectedInt == max) {
                System.out.println(selectedInt + " itself is the highest value in the given array");
            return selectedInt;

        }
    }
    return someIntVar;
}


You're looking for the (n-1)th smallest number in a list, the algorithm to solve this problem is the selection algorithm. But selection by sorting is good enough for most cases (performance O(n log n)).


The following does not work. Thanks for reviewing my answer :-)

  // doesn't work in general!!!
  int[] tal = {3, 8, 5, 8, 2, 3, 9, 12, 21};
  int max=tal[0];
  int previous = max;
  for(int i=0;i<tal.length;i++){
      if(tal[i]>max){      // <- fixed the if statement 
          previous = max;
          max=tal[i];
      }
  }
  System.out.println("Biggest: "+ max);
  System.out.println("2nd Biggest: "+ previous);

This should give 21 (Biggest) and 12 (next biggest)

(answer according to my understanding of the question ;-) )


Option 1:

int[] tal = {3, 8, 5, 8, 2, 3, 9, 12, 21};
int nextMax = tal[0];
int max=tal[0];
for(int i=0;i<tal.length;i++){
  if(tal[i]>max){
      nextMax = max;
      max = tal[i];
  }
}
System.out.println("Biggest: "+ max);
System.out.println("Next biggest: " + nextMax);

Option 2: Run a sort function on the array, and print out the first 2 numbers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜