Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How To Find A Second Largest Element in an Array?

0.00/5 (No votes)
11 Sep 2015 1  
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));

        }
    }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here