Home > Mobile >  Read the second largest number in an array
Read the second largest number in an array

Time:11-13

I've written a console application (.NET 5.0) in C# in Visual Studio which sorts an array from high to low and then it has to print out the second largest element in that array.

Im getting close but ive been trying things for the past 2 hours and I don't get why I always get an out of bounds error at the last 'if'. The program is supposed to detect duplicates so for instance if the input is '1 1 2 2 5 5 9 9" it will print out "5" as it is the second largest.

My current code is below I can't get it to work without crashing

using System;

namespace second_largest
{
    class Program
    {
        static void Main(string[] args)
        {
            double[] input = Array.ConvertAll(Console.ReadLine().Split(" "), Convert.ToDouble);

            for (int repeat = 0; repeat < input.Length; repeat  )
            {
                for (int j = 0; j < input.Length - 1; j  )
                {
                    if(input[j] < input[j 1])
                    {
                        double temp = input[j];
                        input[j] = input[j   1];
                        input[j   1] = temp;
                    }
                }
            }

            for (int i = 0; i < input.Length; i  )
            {
                if(input[i] == input[i   1])
                {

                }
                else
                {
                    Console.WriteLine(input[i]);
                }
                Console.WriteLine(input[i]);
            }
        }
    }
}

CodePudding user response:

There is a much easier way to get the second highest using LINQ

It involves grouping by the number (to eliminate duplicates), then ordering by the grouped key descending, then skipping one and taking one

var secondHighest = nums.GroupBy(n => n)
                        .OrderByDescending(n => n.Key)
                        .Skip(1)
                        .First()
                        .Key;

Live example: https://dotnetfiddle.net/WlFyWr

CodePudding user response:

You see the error because you iterate up to i < input.Length which means that i 1 on the following if statement is out of bounds of the length of the input array. You need to do the same thing you've done on the previous nested for loop:

for(int i = 0; i < input.Length - 1; i )

  • Related