Hello guys, Can anyone Please tell me how to How to find highest ,second highest number, Lowest Second Lowest number in given Array
var numbers = new[] {855,3,64,6,24,75,3,6,24,45};
Any pointer and suggestion would really helpful . Thanks
Hello guys, Can anyone Please tell me how to How to find highest ,second highest number, Lowest Second Lowest number in given Array
var numbers = new[] {855,3,64,6,24,75,3,6,24,45};
Any pointer and suggestion would really helpful . Thanks
You don't specify the complexity requirement: one way is to sort the array in descending order and pick the top, second and third items.
Another is to build a Heap, and then perform remove root 3 times (with the heap being rebuilt after each remove).
Assuming you have at least 2 items in the array you can use OrderBy()
and ElementAt()
:
var numbers = new[] { 855, 3, 64, 6, 24, 75, 3, 6, 24, 45 };
var secondLowest = numbers.OrderBy(num => num).ElementAt(1);
var secondHighest = numbers.OrderBy(num => num).Reverse().ElementAt(1);
Getting the highest and lowest is simpler and can be done using Max()
and Min()
LINQ methods.
var lowest = numbers.Min();
var highest = numbers.Max();
If you're worried about complexity, you can achieve better result using Selection algorithm. Using it you can perform the operations in O(n) complexity.
You can also try this -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class secondHighestLowest : System.Web.UI.Page
{
int[] arr = new int[10] { 45, 3, 64, 6, 24, 75, 3, 6, 24, 45 };
protected void Page_Load(object sender, EventArgs e)
{
secondHighestLowestNumber();
secoundLowestNumber();
}
private void secondHighestLowestNumber()
{
int firstHighestNumber = arr[0];
int secondHighestNumber = arr[0];
for(int i = 0; i<arr.Length; i++)
{
if (arr[i]>firstHighestNumber)
{
firstHighestNumber = arr[i];
}
}
for (int x = 0; x < arr.Length; x++)
{
if (arr[x]>secondHighestNumber && firstHighestNumber!=arr[x])
{
secondHighestNumber = arr[x];
}
}
Response.Write("secondHighestNumber---- " + secondHighestNumber + "</br>");
}
private void secoundLowestNumber()
{
int firstLowestNumber = arr[0];
int secondLowestNumber = arr[0];
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] < firstLowestNumber)
{
firstLowestNumber = arr[i];
}
}
for (int x = 0; x < arr.Length; x++)
{
if (arr[x] < secondLowestNumber && firstLowestNumber != arr[x])
{
secondLowestNumber = arr[x];
}
}
Response.Write("secondLowestNumber---- " + secondLowestNumber + "</br>");
}
}
Hope this is helpful :)