Подтвердить что ты не робот

Поиск второго по величине числа в массиве

Мне трудно понять логику метода, чтобы найти второе наибольшее число в массиве. Используемый метод состоит в том, чтобы найти наивысший массив, но меньше предыдущего (который уже найден). Дело в том, что я до сих пор не могу понять, почему || highest_score == second_highest необходимо. Например, я ввожу три числа: 98, 56, 3. Без него как высшие, так и самые высокие будут 98. Объясните.

int second highest = score[0];  
if (score[i] > second_highest && score[i] < highest_score || highest_score == second_highest)   
    second_highest = score[i];
4b9b3361

Ответ 1

Я не уверен, что выполнение того, что вы сделали, устраняет проблему; Я думаю, что это маскирует еще одну проблему в вашей логике. Найти второе место на самом деле довольно просто:

 static int secondHighest(int... nums) {
    int high1 = Integer.MIN_VALUE;
    int high2 = Integer.MIN_VALUE;
    for (int num : nums) {
      if (num > high1) {
        high2 = high1;
        high1 = num;
      } else if (num > high2) {
        high2 = num;
      }
    }
    return high2;
 }

Это O(N) за один проход. Если вы хотите принять связи, то измените на if (num >= high1), но, как есть, он вернет Integer.MIN_VALUE, если в массиве не будет по крайней мере 2 элемента. Он также вернет Integer.MIN_VALUE, если массив содержит только тот же номер.

Ответ 2

// Initialize these to the smallest value possible
int highest = Integer.MIN_VALUE;
int secondHighest = Integer.MIN_VALUE;

// Loop over the array
for (int i = 0; i < array.Length; i++) {

    // If we've found a new highest number...
    if (array[i] > highest) {

        // ...shift the current highest number to second highest
        secondHighest = highest;

        // ...and set the new highest.
        highest = array[i];
    } else if (array[i] > secondHighest)
        // Just replace the second highest
        secondHighest = array[i];
    }
}

// After exiting the loop, secondHighest now represents the second
// largest value in the array

Изменить:

Упс. Спасибо, что указали на мою ошибку, ребята. Исправлено.

Ответ 3

Если первый элемент, для которого second_highest установлен первоначально, уже является самым высоким элементом, тогда он должен быть переназначен новому элементу, когда будет найден следующий элемент. То есть, он инициализируется до 98 и должен быть установлен на 56. Но 56 не выше 98, поэтому он не будет установлен, если вы не выполните проверку.

Если наибольшее число появляется дважды, это приведет к второму наивысшему значению, а не ко второму элементу, который вы найдете, если вы отсортировали массив.

Ответ 4

Ответы, которые я видел, не работают, если есть два таких же самых больших числа, как в приведенном ниже примере.

        int[] randomIntegers = { 1, 5, 4, 2, 8, 1, 8, 9,9 };
        SortedSet<Integer> set = new TreeSet<Integer>();
        for (int i: randomIntegers) {
            set.add(i);
        }
        // Remove the maximum value; print the largest remaining item
        set.remove(set.last());
        System.out.println(set.last());

Я удалил его из набора не из массива

Ответ 5

 public static int secondLargest(int[] input) {
            int largest,secondLargest;

            if(input[0] > input[1]) {
                largest = input[0];
                secondLargest = input[1];
            }
            else {
                largest = input[1];
                secondLargest = input[0];
            }

            for(int i = 2; i < input.length; i++) {
                if((input[i] <= largest) && input[i] > secondLargest) {
                    secondLargest = input[i];
                }

                if(input[i] > largest) {
                    secondLargest = largest;
                    largest = input[i];
                }
            }

            return secondLargest;
        }

Ответ 6

import java.util.*;
public class SecondLargestNew
{
    public static void main(String args[])
    {
        int[] array = {0,12,74,26,82,3,89,8,94,3};  

    int highest = Integer.MIN_VALUE;
    int secondHighest = Integer.MIN_VALUE;


    for (int i = 0; i < array.length; i++) 
    {
        if (array[i] > highest) 
        {
            // ...shift the current highest number to second highest
            secondHighest = highest;
            // ...and set the new highest.
            highest = array[i];
        } else if (array[i] > secondHighest)
            {
            // Just replace the second highest
            secondHighest = array[i];
            }
    }
    System.out.println("second largest is "+secondHighest );
    System.out.println("largest is "+ highest);
        }
}

enter image description here

Ответ 7

Моя идея состоит в том, что вы предполагаете, что первый и второй члены массива - это ваш первый макс и второй макс. Затем вы берете каждый новый элемент массива и сравниваете его со вторым макс. Не забудьте сравнить 2-й максимум с 1-м. Если он больше, просто замените их.

   public static int getMax22(int[] arr){
    int max1 = arr[0];
    int max2 = arr[1];
    for (int i = 2; i < arr.length; i++){
        if (arr[i] > max2)
        {
            max2 = arr[i];
        }

        if (max2 > max1)
        {
            int temp = max1;
            max1 = max2;
            max2 = temp;
        }
    }
     return max2;
}

Ответ 8

private static int SecondBiggest(int[] vector)
{
    if (vector == null)
    {
        throw new ArgumentNullException("vector");
    }
    if (vector.Length < 2)
    {
        return int.MinValue;
    }

    int max1 = vector[0];
    int max2 = vector[1];
    for (int i = 2; i < vector.Length; ++i)
    {
        if (max1 > max2 && max1 != vector[i])
        {
            max2 = Math.Max(max2, vector[i]);
        }
        else if (max2 != vector[i])
        {
            max1 = Math.Max(max1, vector[i]);
        }
    }
    return Math.Min(max1, max2);
}

Это рассматривает дубликаты как одно и то же число. Вы можете изменить проверку состояния, если хотите, чтобы все самые большие и второй по величине дубликаты.

Ответ 9

Если временная сложность не является проблемой, то вы можете запустить сортировку пузырьков и в течение двух итераций, вы получите свой второй самый высокий номер, потому что на первой итерации цикла наибольшее число будет перенесено на последнее. Во второй итерации второе по величине число будет перемещено рядом с последним.

Ответ 10

Если вы хотите, чтобы 2-й наивысший и самый высокий индекс числа в массиве, тогда...

public class Scoller_student {

    public static void main(String[] args) {
        System.out.println("\t\t\tEnter No. of Student\n");
        Scanner scan = new Scanner(System.in);
        int student_no = scan.nextInt();

        // Marks Array.........
        int[] marks;
        marks = new int[student_no];

        // Student name array.....
        String[] names;
        names = new String[student_no];
        int max = 0;
        int sec = max;
        for (int i = 0; i < student_no; i++) {
            System.out.println("\t\t\tEnter Student Name of id = " + i + ".");

            names[i] = scan.next();
            System.out.println("\t\t\tEnter Student Score of id = " + i + ".\n");

            marks[i] = scan.nextInt();
            if (marks[max] < marks[i]) {
                sec = max;
                max = i;
            } else if (marks[sec] < marks[i] && marks[max] != marks[i]) {
                sec = i;
            }
        }

        if (max == sec) {
            sec = 1;
            for (int i = 1; i < student_no; i++) {
                if (marks[sec] < marks[i]) {
                    sec = i;
                }
            }
        }

        System.out.println("\t\t\tHigherst score id = \"" + max + "\" Name : \""
            + names[max] + "\" Max mark : \"" + marks[max] + "\".\n");
        System.out.println("\t\t\tSecond Higherst score id = \"" + sec + "\" Name : \""
            + names[sec] + "\" Max mark : \"" + marks[sec] + "\".\n");

    }
}

Ответ 11

public class SecondHighest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        /*
         * Find the second largest int item in an unsorted array.
         * This solution assumes we have atleast two elements in the array
         * SOLVED! - Order N. 
         * Other possible solution is to solve with Array.sort and get n-2 element.
         * However, Big(O) time NlgN 
         */

        int[] nums = new int[]{1,2,4,3,5,8,55,76,90,34,91};
        int highest,cur, secondHighest = -1;

        int arrayLength = nums.length;
        highest = nums[1] > nums[0] ? nums[1] : nums[0];
        secondHighest = nums[1] < nums[0] ? nums[1] : nums[0];

        if (arrayLength == 2) {
            System.out.println(secondHighest);

        } else {

            for (int x = 0; x < nums.length; x++) {

                cur = nums[x];
                int tmp;

                if (cur < highest && cur > secondHighest)
                    secondHighest = cur;

                else if (cur > secondHighest && cur > highest) {
                    tmp = highest;
                    highest = cur;
                    secondHighest = tmp;
                }

            }   

            System.out.println(secondHighest);

        }   
    }
}

Ответ 12

public class secondLargestElement 
{
    public static void main(String[] args) 
    {
        int []a1={1,0};
        secondHigh(a1);
    }

    public static void secondHigh(int[] arr)
    {
        try
        {
            int highest,sec_high;
            highest=arr[0];
            sec_high=arr[1];

                for(int i=1;i<arr.length;i++)
                {
                    if(arr[i]>highest)
                    {           
                        sec_high=highest;
                        highest=arr[i]; 
                    }
                    else 
                    // The first condition before the || is to make sure that second highest is not actually same as the highest , think 
                        // about {5,4,5}, you don't want the last  5 to be reported as the sec_high
                        // The other half after || says if the first two elements are same then also replace the sec_high with incoming integer
                        // Think about {5,5,4}
                    if(arr[i]>sec_high && arr[i]<highest || highest==sec_high)
                        sec_high=arr[i];
                }
            //System.out.println("high="+highest +"sec"+sec_high);
            if(highest==sec_high)
                System.out.println("All the elements in the input array are same");
             else
                 System.out.println("The second highest element in the array is:"+ sec_high);

         }

        catch(ArrayIndexOutOfBoundsException e)
        {
        System.out.println("Not enough elements in the array");
        //e.printStackTrace();
        }
    }
}

Ответ 13

Вы можете найти самое большое и третье по величине количество несортированных массивов.

 public class ThirdLargestNumber {
        public static void main(String[] args) {
            int arr[] = { 220, 200, 100, 100, 300, 600, 50, 5000, 125, 785 };
            int first = 0, second = 0, third = 0, firstTemp = 0, secondTemp = 0;
            for (int i = 0; i <= 9 /*
                                     * Length of array-1. You can use here length
                                     * property of java array instead of hard coded
                                     * value
                                     */; i++) {
                if (arr[i] == first) {
                    continue;
                }
                if (arr[i] > first) {
                    firstTemp = first;
                    secondTemp = second;
                    first = arr[i];
                    second = firstTemp;
                    if (secondTemp > third) {
                        third = secondTemp;
                    }
                } else {
                    if ((arr[i] == second) || (arr[i]) == first) {
                        continue;
                    }
                    if ((arr[i] > second) && (arr[i]) < first) {
                        secondTemp = second;
                        second = arr[i];
                        if (secondTemp > third) {
                            third = secondTemp;
                        }
                    } else {
                        if (arr[i] > third) {
                            third = arr[i];
                        }
                    }
                }
            }
            // System.out.println("Third largest number: " + third);
            System.out.println("Second largest number: " + second);
            // System.out.println("Largest number: " + first);
        }
    }

Ответ 14

Я думаю, что для поиска второго Высшего нет нам нужны эти строки, если мы можем использовать встроенную функцию

int[] randomIntegers = {1, 5, 4, 2, 8, 1, 1, 6, 7, 8, 9};
    Arrays.sort(randomIntegers);
    System.out.println(randomIntegers[randomIntegers.length-2]);

Ответ 15

Я предлагаю решение не в программе JAVA (написанное на JavaScript), но для поиска наивысшего и второго по величине числа требуется итерация o (n/2).
Ссылка рабочего скрипача Ссылка Fiddler

 var num=[1020215,2000,35,2,54546,456,2,2345,24,545,132,5469,25653,0,2315648978523];
var j=num.length-1;
var firstHighest=0,seoncdHighest=0;
num[0] >num[num.length-1]?(firstHighest=num[0],seoncdHighest=num[num.length-1]):(firstHighest=num[num.length-1],   seoncdHighest=num[0]);
j--;
for(var i=1;i<=num.length/2;i++,j--)
{
   if(num[i] < num[j] )
   {
          if(firstHighest < num[j]){
          seoncdHighest=firstHighest;
           firstHighest= num[j];
          }
           else if(seoncdHighest < num[j] ) {
               seoncdHighest= num[j];

           }
   }
   else {
       if(firstHighest < num[i])
       {
           seoncdHighest=firstHighest;
           firstHighest= num[i];

       }
       else if(seoncdHighest < num[i] ) {
            seoncdHighest= num[i];

       }
   }

}         

Ответ 16

public class SecondandThirdHighestElement {
    public static void main(String[] args) {
        int[] arr = {1,1,2,3,8,1,2,3,3,3,2,3,101,6,6,7,8,8,1001,99,1,0};
        // create three temp variable and store arr of first element in that temp variable so that it will compare with other element
        int firsttemp = arr[0];
        int secondtemp = arr[0];
        int thirdtemp = arr[0];
        //check and find first highest value from array by comparing with other elements if found than save in the first temp variable 
        for (int i = 0; i < arr.length; i++) {
            if(firsttemp <arr[i]){
                firsttemp =  arr[i];
            }//if

        }//for
        //check and find the second highest variable by comparing with other elements in an array and find the element and that element should be smaller than first element array
        for (int i = 0; i < arr.length; i++) {
            if(secondtemp < arr[i] && firsttemp>arr[i]){
                secondtemp = arr[i];
            }//if
        }//for
        //check and find the third highest variable by comparing with other elements in an array and find the element and that element should be smaller than second element array

        for (int i = 0; i < arr.length; i++) {
            if(thirdtemp < arr[i] && secondtemp>arr[i]){
                thirdtemp = arr[i];
            }//if
        }//for

        System.out.println("First Highest Value:"+firsttemp);
        System.out.println("Second Highest Value:"+secondtemp);
        System.out.println("Third Highest  Value:"+thirdtemp);

    }//main
}//class

Ответ 17

Если этот вопрос у интервьюера, пожалуйста, НЕ ПРИНИМАЙТЕ СООТВЕТСТВИЕ ТЕХНОЛОГИИ ИЛИ НЕ ИСПОЛЬЗУЙТЕ любые встроенные методы, такие как Arrays.sort или Collection.sort. Цель этих вопросов заключается в том, насколько оптимально ваше решение в плане производительности, поэтому лучший вариант будет реализован только с вашей собственной логикой с помощью реализации O (n-1). Данный код предназначен исключительно для начинающих, а не для опытных парней.

  public void printLargest(){


    int num[] ={ 900,90,6,7,5000,4,60000,20,3};

    int largest = num[0];

    int secondLargest = num[1];

    for (int i=1; i<num.length; i++)
    {
        if(largest < num[i])
        {
            secondLargest = largest;
            largest = num[i];


        }
        else if(secondLargest < num[i]){
            secondLargest = num[i];
        }
    }
    System.out.println("Largest : " +largest);
    System.out.println("Second Largest : "+secondLargest);
}

Ответ 18

Второй по величине в O (n/2)

public class SecMaxNum {

    // second Largest number with O(n/2)
    /**
     * @author Rohan Kamat
     * @Date Feb 04, 2016
     */
    public static void main(String[] args) {
        int[] input = { 1, 5, 10, 11, 11, 4, 2, 8, 1, 8, 9, 8 };
        int large = 0, second = 0;

        for (int i = 0; i < input.length - 1; i = i + 2) {
            // System.out.println(i);
            int fist = input[i];
            int sec = input[i + 1];
            if (sec >= fist) {
                int temp = fist;
                fist = sec;
                sec = temp;
            }
            if (fist >= second) {
                if (fist >= large) {
                    large = fist;
                } else {
                    second = fist;
                }

            }

            if (sec >= second) {
                if (sec >= large) {
                    large = sec;
                } else {
                    second = sec;
                }
            }
        }
    }
}

Ответ 19

Проблема: Проблема состоит в том, чтобы получить второй по величине элемент массива.

Наблюдение: Второе по величине число определяется как число, которое имеет минимальную разницу при вычитании из максимального элемента в массиве.

Решение: Это двухпроходное решение. Первый проход - найти максимальное число. Второй проход - найти элемент с минимальной разницей с максимальным элементом по сравнению с другими элементами массива. Пример: в массиве [2, 3, 6, 6, 5] максимум = 6 и второй максимум = 5, так как он имеет минимальную разницу с максимальным элементом 6 - 5 = 1, решение для второго наибольшего = 5

function printSecondMax(myArray) {
  var x, max = myArray[0];
  // Find maximum element 
  for(x in myArray){
     if(max < myArray[x]){
        max = myArray[x];
     }
  }
  var secondMax = myArray[0], diff = max - secondMax;
  // Find second max, an element that has min diff with the max
  for(x in myArray){
    if(diff != 0 && (max - myArray[x]) != 0 && diff > (max - myArray[x])){
        secondMax = myArray[x];
        diff = max - secondMax;
    }
  }
  console.log(secondMax);
}

Сложность: O (n). Это самый простой способ сделать это.

Для более эффективного определения максимального элемента можно заглянуть в max heap, вызов max-heapify займет время O (log n) чтобы найти max, а затем щелкнуть верхний элемент, даст максимум. Чтобы получить второй максимум, max-heapify после всплытия сверху и продолжения всплывания, пока вы не получите число, которое меньше максимального. Это будет второй максимум. Это решение имеет сложность O (n log n).

Ответ 20

Попробуйте следующее: используя этот метод, вы можете оштрафовать второе по величине число в массиве с четным массивом, содержащим случайное число. Первый цикл используется для решения проблемы, если наибольшее число приходит первым индексом массива.

public class secondLargestnum {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] array = new int[6];
        array[0] = 10;
        array[1] = 80;
        array[2] = 5;
        array[3] = 6;
        array[4] = 50;
        array[5] = 60;
        int tem = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[0]>array[i]) {
                tem = array[0];
            array[0] = array[array.length-1];
            array[array.length-1] = tem;
            }
        }
        Integer largest = array[0];
        Integer second_largest = array[0];

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

            if (largest<array[i]) {
                second_large = largest;
                largest = array[i];
            }
            else if (second_large<array[i]) {
                second_large = array[i];

            }

        }
System.out.println("largest number "+largest+" and second largest number "+second_largest);

    }

}

Ответ 21

открытый класс SecondHighInIntArray {

public static void main(String[] args) {
    int[] intArray=new int[]{2,2,1};
            //{2,2,1,12,3,7,9,-1,-5,7};
    int secHigh=findSecHigh(intArray);
    System.out.println(secHigh);
}

private static int findSecHigh(int[] intArray) {

    int highest=Integer.MIN_VALUE;
    int sechighest=Integer.MIN_VALUE;
    int len=intArray.length;
    for(int i=0;i<len;i++)
    {
        if(intArray[i]>highest)
        {
            sechighest=highest;
            highest=intArray[i];
            continue;
        }

        if(intArray[i]<highest && intArray[i]>sechighest)
        {
            sechighest=intArray[i];
            continue;
        }


    }
    return sechighest;
}

}

Ответ 22

Используйте следующую функцию
`

public static int secHigh(int arr[]){
            int firstHigh = 0,secHigh = 0;
            for(int x: arr){
                if(x > firstHigh){
                    secHigh = firstHigh;
                    firstHigh = x;
                }else if(x > secHigh){
                    secHigh = x;
                }
            }
            return secHigh;
        }

Вызов функции

int secondHigh = secHigh(arr);

Ответ 23

import java.util.Scanner;

public class SecondLargest {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter size of array : ");
        int n = sc.nextInt();
        int ar[] = new int[n];
        for(int i=0;i<n;i++)
        {
            System.out.print("Enter value for array : ");
            ar[i] = sc.nextInt();
        }
        int m=ar[0],m2=ar[0];
        for(int i=0;i<n;i++)
        {
            if(ar[i]>m)
                m=ar[i];
        }
        for(int i=0;i<n;i++)
        {
            if(ar[i]>m2 && ar[i]<m)
                m2=ar[i];
        }
        System.out.println("Second largest : "+m2);
        sc.close();
    }
}

Ответ 24

public void findMax(int a[]) {
    int large = Integer.MIN_VALUE;
    int secondLarge = Integer.MIN_VALUE;
    for (int i = 0; i < a.length; i++) {
        if (large < a[i]) {
            secondLarge = large;
            large = a[i];
        } else if (a[i] > secondLarge) {
            if (a[i] != large) {
                secondLarge = a[i];
            }
        }
    }
    System.out.println("Large number " + large + " Second Large  number " + secondLarge);
}

Вышеприведенный код был протестирован с целыми массивами, имеющими повторяющиеся записи, отрицательные значения. Наибольшее количество и второе по величине число возвращаются за один проход. Этот код только терпит неудачу, если массив содержит только несколько экземпляров такого же числа, как {8,8,8,8} или имеет только одно число.

Ответ 25

public class SecondLargestNumber
{
  public static void main(String[] args)
  {
    int[] var={-11,-11,-11,-11,115,-11,-9};
    int largest = 0;
    int secLargest = 0;
    if(var.length == 1)
    {
      largest = var[0];
      secLargest = var[0];
    }
    else if(var.length > 1)
    {
      largest= var[0];
      secLargest = var[1];
      for(int i=1;i<var.length;i++)
      {
        if(secLargest!=largest)
        {
          if(var[i]>largest)
          { 
            secLargest = largest;
            largest = var[i];
          }
          else if(var[i]>secLargest && var[i] != largest)
          {
            secLargest= var[i];
          }
        }
        else
        {
          if(var[i]>largest)
          {
           secLargest = largest;
           largest = var[i];
          }
          else
          {
           secLargest = var[i];
          }
       }
    }
  }

    System.out.println("Largest: "+largest+" Second Largest: "+secLargest);
  }
}

Ответ 26

   /* Function to print the second largest elements */
    void print2largest(int arr[], int arr_size)
    {
   int i, first, second;

   /* There should be atleast two elements */
   if (arr_size < 2)
   {
    printf(" Invalid Input ");
    return;
    }

   first = second = INT_MIN;
   for (i = 0; i < arr_size ; i ++)
   {
    /* If current element is smaller than first
       then update both first and second */
    if (arr[i] > first)
    {
        second = first;
        first = arr[i];
    }

    /* If arr[i] is in between first and 
       second then update second  */
    else if (arr[i] > second && arr[i] != first)
        second = arr[i];
   }
   if (second == INT_MIN)
    printf("There is no second largest elementn");
    else
    printf("The second largest element is %dn", second);
    }

Ответ 27

У меня есть простейшая логика, чтобы найти второе по величине число, это не так. Логика находит сумму двух чисел в массиве, которая имеет самое высокое значение, а затем проверяет, какая из двух простых............

int ar[]={611,4,556,107,5,55,811};
int sum=ar[0]+ar[1];
int temp=0;
int m=ar[0];
int n=ar[1];
for(int i=0;i<ar.length;i++){
    for(int j=i;j<ar.length;j++){
        if(i!=j){
        temp=ar[i]+ar[j];
        if(temp>sum){
            sum=temp;
            m=ar[i];
            n=ar[j];
        }
        temp=0;

    }
    }
}
if(m>n){
    System.out.println(n);

}
else{
    System.out.println(m);
}

Ответ 28

импортировать java.util.Scanner;

открытый класс SecondHighestFromArrayTest {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter size of Array");
    int size = scan.nextInt();
    int[] arr = new int[size];
    for (int i = 0; i < size; i++) {
        arr[i] = scan.nextInt();
    }
    System.out.println("second highest element " + getSecondHighest(arr));
}

public static int getSecondHighest(int arr[]) {
    int firstHighest = arr[0];
    int secondHighest = arr[0];
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] > firstHighest) {
            secondHighest = firstHighest;
            firstHighest = arr[i];
        } else if (arr[i] > secondHighest) {
            secondHighest = arr[i];
        }
    }
    return secondHighest;
}

}

Ответ 29

Самый простой способ -

public class SecondLargest {
    public static void main(String[] args) {
        int[] arr = { 1, 2, 5, 6, 3 };

        int first = Integer.MIN_VALUE;
        int second = Integer.MIN_VALUE;
        for (int i = 0; i < arr.length; i++) {
            // If current element is smaller than first then update both first
            // and second
            if (arr[i] > first) {
                second = first;
                first = arr[i];
            }
            // If arr[i] is in between first and second then update second
            else if (arr[i] > second && arr[i] != first) {
                second = arr[i];
            }
        }
    }
}

Ответ 30

Второй по величине элемент в массиве: IN Java:

class test2{
    public static void main(String[] args) {

int a[] = {1,2,3,9,5,7,6,4,8};
Arrays.sort(a);
int aa = a[a.length -2 ];
System.out.println(aa);


    }//main

}//end

В Python:

a = [1, 2, 3, 9, 5, 7, 6, 4, 8]

aa = sorted(list(a))
print(aa)
aaa = aa[-2]
print(aaa)