65.9K
CodeProject is changing. Read more.
Home

How To Find A Second Largest Element in an Array?

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.71/5 (4 votes)

Sep 11, 2015

CPOL
viewsIcon

14844

Finding the second largest element in an array using Linq

Introduction

The code snippet below will show you how to find a second largest element in an array:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MSMUTest
{
    class Program
    {
        /*
         * Write a function that accepts an array of non-negative integers and 
         * returns the second largest integer in the array. Return -1 if there is no second largest.
         */

        public int [] AcceptArrayElements(int count)
        {
            int[] inputElement = new int[count];
            for (int cnt = 0; cnt < count; cnt++)
            {
                inputElement[cnt] = Convert.ToInt32(Console.ReadLine());
            }
            return inputElement;
        }
        

 public int FindSecondLargestElement(int[] inputElements)
        {

            var result = (from elements in inputElements
                          orderby elements descending
                          select elements).Distinct().Skip(1).Take(1);
#region ForBeginners
            // May use below code block if not much versed in linq.
            //var result = (from elements in inputElements
            //              orderby elements descending
            //              select elements
          //  int scndLargestNumber = -1;
            //int [] finalArray = result.ToArray();
            //for (int cnt = 0; cnt < finalArray.Length; cnt++)
            //{
               
            //    if ( finalArray[cnt] < finalArray[0])
            //    {
            //        scndLargestNumber = finalArray[cnt];
            //        break;
            //    }
               
            //}
#endregion

            return result.FirstOrDefault();
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Please Enter Count");
            int count =Convert.ToInt32( Console.ReadLine());
            Program test = new Program();
            Console.WriteLine("Enter Your Number");
            int[] inputElements = test.AcceptArrayElements(count);
            for (int cnt = 0; cnt < inputElements.Length; cnt++)
            {
                Console.WriteLine("Your Input Element At Position {0} is {1}.", 
					cnt, inputElements[cnt]);
            }
            Console.WriteLine("Second Largest Element In Your Provided Input Is {0} ", 
				test.FindSecondLargestElement(inputElements));

        }
    }
}