Related
Tried to googled it but with no luck.
How can I find the second maximum number in an array with the smallest complexity?
code OR idea will be much help.
I can loop through an array and look for the maximum number
after that, I have the maximum number and then loop the array again to find the second the same way.
But for sure it is not efficient.
You could sort the array and choose the item at the second index, but the following O(n) loop will be much faster.
int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 };
int largest = int.MinValue;
int second = int.MinValue;
foreach (int i in myArray)
{
if (i > largest)
{
second = largest;
largest = i;
}
else if (i > second)
second = i;
}
System.Console.WriteLine(second);
OR
Try this (using LINQ):
int secondHighest = (from number in test
orderby number descending
select number).Distinct().Skip(1).First()
How to get the second highest number in an array in Visual C#?
Answer in C# :
static void Main(string[] args)
{
//let us define array and vars
var arr = new int[]{ 100, -3, 95,100,95, 177,-5,-4,177,101 };
int biggest =0, secondBiggest=0;
for (int i = 0; i < arr.Length; ++i)
{
int arrItem = arr[i];
if(arrItem > biggest)
{
secondBiggest = biggest; //always store the prev value of biggest
//to second biggest...
biggest = arrItem;
}
else if (arrItem > secondBiggest && arrItem < biggest) //if in our
//iteration we will find a number that is bigger than secondBiggest and smaller than biggest
secondBiggest = arrItem;
}
Console.WriteLine($"Biggest Number:{biggest}, SecondBiggestNumber:
{secondBiggest}");
Console.ReadLine(); //make program wait
}
Output : Biggest Number:177, SecondBiggestNumber:101
public static int F(int[] array)
{
array = array.OrderByDescending(c => c).Distinct().ToArray();
switch (array.Count())
{
case 0:
return -1;
case 1:
return array[0];
}
return array[1];
}
static void Main(string[] args)
{
int[] myArray = new int[] { 0, 11, 2, 15, 16, 8, 16 ,8,15};
int Smallest = myArray.Min();
int Largest = myArray.Max();
foreach (int i in myArray)
{
if(i>Smallest && i<Largest)
{
Smallest=i;
}
}
System.Console.WriteLine(Smallest);
Console.ReadLine();
}
This will work even if you have reputation of items in an array
int[] arr = {-10, -3, -3, -6};
int h = int.MinValue, m = int.MinValue;
foreach (var t in arr)
{
if (t == h || t == m)
continue;
if (t > h)
{
m = h;
h = t;
}
else if(t > m )
{
m = t;
}
}
Console.WriteLine("High: {0} 2nd High: {1}", h, m);
//or,
m = arr.OrderByDescending(i => i).Distinct().Skip(1).First();
Console.WriteLine("High: {0} 2nd High: {1}", h, m);
/* we can use recursion */
var counter = 0;
findSecondMax = (arr)=> {
let max = Math.max(...arr);
counter++;
return counter == 1 ? findSecondMax(arr.slice(0,arr.indexOf(max)).concat(arr.slice(arr.indexOf(max)+1))) : max;
}
console.log(findSecondMax([1,5,2,3,0]))
static void Main(string[] args){
int[] arr = new int[5];
int i, j,k;
Console.WriteLine("Enter Array");
for (i = 0; i < 5; i++) {
Console.Write("element - {0} : ", i);
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("\nElements in array are: ");
j=arr[0];
k=j;
for (i = 1; i < 5; i++) {
if (j < arr[i])
{
if(j>k)
{
k=j;
}
j=arr[i];
}
}
Console.WriteLine("First Greatest element: "+ j);
Console.WriteLine("Second Greatest element: "+ k);
Console.Write("\n");
}
int max = 0;
int secondmax = 0;
int[] arr = { 2, 11, 15, 1, 7, 99, 6, 85, 4 };
for (int r = 0; r < arr.Length; r++)
{
if (max < arr[r])
{
max = arr[r];
}
}
for (int r = 0; r < arr.Length; r++)
{
if (secondmax < arr[r] && arr[r] < max)
{
secondmax = arr[r];
}
}
Console.WriteLine(max);
Console.WriteLine(secondmax);
Console.Read();
Python 36>=
def sec_max(array: list) -> int:
_max_: int = max(array)
second: int = 0
for element in array:
if second < element < _max_:
second = element
else:
continue
return second
Using below code we can find out second highest number, even array contains multiple max numbers
// int[] myArray = { 25, 25, 5, 20, 50, 23, 10 };
public static int GetSecondHighestNumberForUniqueNumbers(int[] numbers)
{
int highestNumber = 0, Seconhight = 0;
List<int> numberList = new List<int>();
for (int i = 0; i < numbers.Length; i++)
{
//For loop should move forward only for unique items
if (numberList.Contains(numbers[i]))
continue;
else
numberList.Add(numbers[i]);
//find higest number
if (highestNumber < numbers[i])
{
Seconhight = highestNumber;
highestNumber = numbers[i];
} //find second highest number
else if (Seconhight < numbers[i])
{
Seconhight = numbers[i];
}
}
It's not like that your structure is a tree...It's just a simple array, right?
The best solution is to sort the array. And depending on descending or ascending, display the second or the 2nd last element respectively.
The other alternative is to use some inbuilt methods, to get the initial max. Pop that element, and then search for the max again. Don't know C#, so can't give the direct code.
You'd want to sort the numbers, then just take the second largest. Here's a snippet without any consideration of efficiency:
var numbers = new int[] { 3, 5, 1, 5, 4 };
var result=numbers.OrderByDescending(x=>x).Distinct().Skip(1).First();
This isn't too bad:
int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 };
var secondMax =
myArray.Skip(2).Aggregate(
myArray.Take(2).OrderByDescending(x => x).AsEnumerable(),
(a, x) => a.Concat(new [] { x }).OrderByDescending(y => y).Take(2))
.Skip(1)
.First();
It's fairly low on complexity as it only every sorts a maximum of three elements
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int size;
Console.WriteLine("Enter the size of array");
size = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the element of array");
int[] arr = new int[size];
for (int i = 0; i < size; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
int length = arr.Length;
Program program = new Program();
program.SeconadLargestValue(arr, length);
}
private void SeconadLargestValue(int[] arr, int length)
{
int maxValue = 0;
int secondMaxValue = 0;
for (int i = 0; i < length; i++)
{
if (arr[i] > maxValue)
{
secondMaxValue = maxValue;
maxValue = arr[i];
}
else if(arr[i] > secondMaxValue)
{
secondMaxValue = arr[i];
}
}
Console.WriteLine("First Largest number :"+maxValue);
Console.WriteLine("Second Largest number :"+secondMaxValue);
Console.ReadLine();
}
}
}
My solution below.
class Program
{
static void Main(string[] args)
{
Program pg = new Program();
Console.WriteLine("*****************************Program to Find 2nd Highest and 2nd lowest from set of values.**************************");
Console.WriteLine("Please enter the comma seperated numbers : ");
string[] val = Console.ReadLine().Split(',');
int[] inval = Array.ConvertAll(val, int.Parse); // Converts Array from one type to other in single line or Following line
// val.Select(int.Parse)
Array.Sort(inval);
Console.WriteLine("2nd Highest is : {0} \n 2nd Lowest is : {1}", pg.Return2ndHighest(inval), pg.Return2ndLowest(inval));
Console.ReadLine();
}
//Method to get the 2nd lowest and 2nd highest from list of integers ex 1000,20,-10,40,100,200,400
public int Return2ndHighest(int[] values)
{
if (values.Length >= 2)
return values[values.Length - 2];
else
return values[0];
}
public int Return2ndLowest(int[] values)
{
if (values.Length > 2)
return values[1];
else
return values[0];
}
}
I am giving solution that's in JavaScript, it takes o(n/2) complexity to find the highest and second highest number.
here is the working Fiddler Link
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];
}
}
}
Sort the array and take the second to last value?
var result = (from elements in inputElements
orderby elements descending
select elements).Distinct().Skip(1).Take(1);
return result.FirstOrDefault();
namespace FindSecondLargestNumber
{
class Program
{
static void Main(string[] args)
{
int max=0;
int smax=0;
int i;
int[] a = new int[20];
Console.WriteLine("enter the size of the array");
int n = int.Parse(Console.ReadLine());
Console.WriteLine("elements");
for (i = 0; i < n; i++)
{
a[i] = int.Parse(Console.ReadLine());
}
for (i = 0; i < n; i++)
{
if ( a[i]>max)
{
smax = max;
max= a[i];
}
else if(a[i]>smax)
{
smax=a[i];
}
}
Console.WriteLine("max:" + max);
Console.WriteLine("second max:"+smax);
Console.ReadLine();
}
}
}
This program will sort numbers and depending if they are greater than or less than 100, put them into their own array.
The problem I have is printing this array. I would like the last number on the line, to not be followed by a space. I have tried many many times to get this to work now and figured I'd ask here.
I know of Console.Write("\b"); but I prefer to find a way of editing the loop so I don't have to do this. Here is the code:
using System;
using System.Linq;
class SplitArray
{
public static void Main(string[] args)
{
int[] myArray = GetNumbersFromConsole();
int[] smallNumbers = new int[myArray.Length];
int[] bigNumbers = new int[myArray.Length];
int bigIndex = 0;
int littleIndex = 0;
for (int i = 0; i < myArray.Length; i++)
{
if(myArray[i] > 100)
{
bigNumbers[bigIndex++] = myArray[i];
}
else if(myArray[i] < 100)
{
smallNumbers[littleIndex++] = myArray[i];
}
}
Console.Write("Big: ");
for (int i = 1; i < bigIndex; ++i)
{
Console.Write(bigNumbers[i]);
Console.Write(" ");
}
Console.WriteLine();
//Console.WriteLine($"{bigNumbers[0]}");
Console.Write("Little: ");
for (int i = 0; i < littleIndex; i++)
{
Console.Write($"{smallNumbers[i]}");
Console.Write(" ");
}
Console.ReadLine();
}
static int[] GetNumbersFromConsole()
{
int count = int.Parse(Console.ReadLine());
int[] result = new int[count];
for (int i = 0; i < count; ++i)
{
result[i] = int.Parse(Console.ReadLine());
}
return result;
}
}
You could just capture your Console.Write(" "); in an if statement.
if(i != littleIndex - 1)
{
Console.Write(" ");
}
littleIndex - 1 is the last time your loop executes, so this will just prevent it from adding the trailing white space. Just do the same for your big numbers as you're printing them out.
There is a builtin utility string.Join
var str = string.Join(" ",bigNumbers);
Console.WriteLine("Big: " + str);
I was playing around some more and just thought I'd try posting the first object in the array before running this loop (also changed loop so the first item didn't get printed twice).
Thank you everyone - I solved it! :)
using System;
using System.Linq;
namespace Arrays
{
class SplitArray
{
public static void Main(string[] args)
{
int[] myArray = GetNumbersFromConsole();
int[] smallNumbers = new int[myArray.Length];
int[] bigNumbers = new int[myArray.Length];
int bigIndex = 0;
int littleIndex = 0;
for (int i = 0; i < myArray.Length; i++)
{
if(myArray[i] > 100)
{
bigNumbers[bigIndex++] = myArray[i];
}
else if(myArray[i] < 100)
{
smallNumbers[littleIndex++] = myArray[i];
}
}
Console.Write("Big: ");
Console.Write($"{bigNumbers[0]} ");
for (int i = 1; i < bigIndex; i++)
{
Console.Write(bigNumbers[i]);
if (i != bigIndex - 1)
{
Console.Write(" ");
}
}
Console.WriteLine();
Console.Write("Little: ");
Console.Write($"{smallNumbers[0]} ");
for (int i = 1; i < littleIndex; i++)
{
Console.Write($"{smallNumbers[i]}");
if (i != littleIndex - 1)
{
Console.Write(" ");
}
}
Console.ReadLine();
}
static int[] GetNumbersFromConsole()
{
int count = int.Parse(Console.ReadLine());
int[] result = new int[count];
for (int i = 0; i < count; ++i)
{
result[i] = int.Parse(Console.ReadLine());
}
return result;
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm currently doing an assignment where I need to find the errors in a program that is preventing it from executing. Its a comparison sort program where there are two sorting methods being compared, Merge Sort and Counting Sort. Its giving me the "No overload for (insert method), takes 1 arguments" message, but I'm unable to find or fix what's giving it the errors, any general idea or fixes to make the comparison work would be appreciated.
using System;
using System.Collections;
namespace Sort
{
class Program
{
static void Main(string[] args)
{
Random rdm = new Random();
ArrayList data = new ArrayList();
ArrayList dataB = new ArrayList();
int size = 50000;
int[] dta = new int[size];
int[] dta50 = new int[50];
int randomNum;
DateTime startTime, endTime;
int i;
// Show both methods worked
for (i = 0; i < 50; i++)
{
randomNum = rdm.Next(100);
data.Add(randomNum);
dta50[i] = randomNum;
}
dataB = CountingSort(data);
PrintArray("Merge Sort:", dataB);
MergeSort(dta50);
Console.WriteLine();
Console.WriteLine("\nCounting Sort:");
Console.WriteLine();
for (int x = 0; x < 50; x++)
Console.Write(dta50[x] + " ");
Console.WriteLine();
Console.WriteLine("\nCounting Sort\tMerge Sort");
for (int n = 1; n < 20; n++) // run 20 times
{
data.Clear();
for (i = 0; i < size; i++)
{
randomNum = rdm.Next(size);
data.Add(randomNum);
dta[i] = randomNum;
}
// Counting Sorting
startTime = DateTime.Now;
CountingSort(data);
endTime = DateTime.Now;
TimeSpan howlong = endTime.Subtract(startTime);
Console.Write(" {0}ms", howlong.Milliseconds);
// Merge Sorting
startTime = DateTime.Now;
MergeSort(dta);
endTime = DateTime.Now;
TimeSpan howlong1 = endTime.Subtract(startTime);
Console.WriteLine("\t\t{0}ms", howlong1.Milliseconds);
}
Console.ReadLine();
}
public static void MergeSort(int[] input, int left, int right)
{
if (left < right)
{
int middle = (left + right) / 2;
MergeSort(input, left, middle);
MergeSort(input, middle + 1, right);
//Merge
int[] leftArray = new int[middle - left + 1];
int[] rightArray = new int[right - middle];
Array.Copy(input, left, leftArray, 0, middle - left + 1);
Array.Copy(input, middle + 1, rightArray, 0, right - middle);
int i = 0;
int j = 0;
for (int k = left; k < right + 1; k++)
{
if (i == leftArray.Length)
{
input[k] = rightArray[j];
j++;
}
else if (j == rightArray.Length)
{
input[k] = leftArray[i];
i++;
}
else if (leftArray[i] <= rightArray[j])
{
input[k] = leftArray[i];
i++;
}
else
{
input[k] = rightArray[j];
j++;
}
}
}
}
private static int[] CountingSort(int[] arr, int min, int max)
{
int[] count = new int[max - min + 1];
int z = 0;
for (int i = 0; i < count.Length; i++) { count[i] = 0; }
for (int i = 0; i < arr.Length; i++) { count[arr[i] - min]++; }
for (int i = min; i <= max; i++)
{
while (count[i - min]-- > 0)
{
arr[z] = i;
z++;
}
}
return arr;
}
static void PrintArray(string title, ArrayList dt)
{
int cc = 0;
Console.WriteLine("\n" + title + "\n");
foreach (int item in dt)
{
if (cc < 10)
Console.Write("{0,4}", item);
else
{ Console.WriteLine(); cc = 0; }
}
}
}
}
Look at your functions:
public static void MergeSort(int[] input, int left, int right)
private static int[] CountingSort(int[] arr, int min, int max)
They each expect three values when you invoke them. Look at how you invoke them:
MergeSort(dta50);
CountingSort(data);
MergeSort(dta);
You're supplying one value, not three.
Elsewhere you invoke them differently:
MergeSort(input, left, middle);
MergeSort(input, middle + 1, right);
In those cases you supply three values.
You need to supply the functions with the values it requires. Otherwise the code has no way of knowing what to do.
Im writing a program where the user writes how many times he want to throw x-number dice and how many sides they going to have.
But i cant figure out how to return the sum om the number on each dice game..
this is the main code:
static void Main(string[] args)
{
List<Dice> _Dice = new List<Dice>();
int a = 0;
int ggr = int.Parse(Interaction.InputBox("How many times do you want to repeat:"));
while (a != ggr)
{
int xChoice = int.Parse(Interaction.InputBox("How many dice do you want to throw:"));
int yChoice = int.Parse(Interaction.InputBox("Write how many sides the dice will have:"));
_Dice.Add(new Dice(xChoice,yChoice));
a++;
}
int e = 1;
foreach (var item in _Dice)
{
Interaction.MsgBox(string.Format("Result off game {0}: {1}", e++, item.ToString()));
}
}
This is the Dice class:
static int _xChoice, _yChoice;
static int[,] dice = new int[_xChoice, _yChoice];
public int Tostring()
{
int a = 0;
foreach (var item in dice)
{
a+=item;
}
return a;
}
void throw()
{
Random r = new Random();
for (int i = 0; i <dice.GetLength(0); i++)
{
for (int j = 0; j < dice.GetLength(1); j++)
{
dice[i, j] = r.Next(1, _yChoice);
}
}
}
public Dice(int Xchoice, int Ychoice)
{
_xChoice = Xchoice;
_yChoice = Ychoice;
}
Just for completeness, what you are asking for is the sum of items of a 2D array:
int total = Enumerable.Range(0, _xChoice).Sum(s => Enumerable.Range(0, _yChoice).Sum(p => dice[s, p]));
Well you can do it like this:
void throw()
{
Random r = new Random();
for (int i = 0; i <dice.GetLength(0); i++)
{
int totalSum = 0;
for (int j = 0; j < dice.GetLength(1); j++)
{
dice[i, j] = r.Next(1, _yChoice);
totalSum += dice[i, j];
}
// Here you display totalSum for game with index i.
}
}
Tried to googled it but with no luck.
How can I find the second maximum number in an array with the smallest complexity?
code OR idea will be much help.
I can loop through an array and look for the maximum number
after that, I have the maximum number and then loop the array again to find the second the same way.
But for sure it is not efficient.
You could sort the array and choose the item at the second index, but the following O(n) loop will be much faster.
int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 };
int largest = int.MinValue;
int second = int.MinValue;
foreach (int i in myArray)
{
if (i > largest)
{
second = largest;
largest = i;
}
else if (i > second)
second = i;
}
System.Console.WriteLine(second);
OR
Try this (using LINQ):
int secondHighest = (from number in test
orderby number descending
select number).Distinct().Skip(1).First()
How to get the second highest number in an array in Visual C#?
Answer in C# :
static void Main(string[] args)
{
//let us define array and vars
var arr = new int[]{ 100, -3, 95,100,95, 177,-5,-4,177,101 };
int biggest =0, secondBiggest=0;
for (int i = 0; i < arr.Length; ++i)
{
int arrItem = arr[i];
if(arrItem > biggest)
{
secondBiggest = biggest; //always store the prev value of biggest
//to second biggest...
biggest = arrItem;
}
else if (arrItem > secondBiggest && arrItem < biggest) //if in our
//iteration we will find a number that is bigger than secondBiggest and smaller than biggest
secondBiggest = arrItem;
}
Console.WriteLine($"Biggest Number:{biggest}, SecondBiggestNumber:
{secondBiggest}");
Console.ReadLine(); //make program wait
}
Output : Biggest Number:177, SecondBiggestNumber:101
public static int F(int[] array)
{
array = array.OrderByDescending(c => c).Distinct().ToArray();
switch (array.Count())
{
case 0:
return -1;
case 1:
return array[0];
}
return array[1];
}
static void Main(string[] args)
{
int[] myArray = new int[] { 0, 11, 2, 15, 16, 8, 16 ,8,15};
int Smallest = myArray.Min();
int Largest = myArray.Max();
foreach (int i in myArray)
{
if(i>Smallest && i<Largest)
{
Smallest=i;
}
}
System.Console.WriteLine(Smallest);
Console.ReadLine();
}
This will work even if you have reputation of items in an array
int[] arr = {-10, -3, -3, -6};
int h = int.MinValue, m = int.MinValue;
foreach (var t in arr)
{
if (t == h || t == m)
continue;
if (t > h)
{
m = h;
h = t;
}
else if(t > m )
{
m = t;
}
}
Console.WriteLine("High: {0} 2nd High: {1}", h, m);
//or,
m = arr.OrderByDescending(i => i).Distinct().Skip(1).First();
Console.WriteLine("High: {0} 2nd High: {1}", h, m);
/* we can use recursion */
var counter = 0;
findSecondMax = (arr)=> {
let max = Math.max(...arr);
counter++;
return counter == 1 ? findSecondMax(arr.slice(0,arr.indexOf(max)).concat(arr.slice(arr.indexOf(max)+1))) : max;
}
console.log(findSecondMax([1,5,2,3,0]))
static void Main(string[] args){
int[] arr = new int[5];
int i, j,k;
Console.WriteLine("Enter Array");
for (i = 0; i < 5; i++) {
Console.Write("element - {0} : ", i);
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("\nElements in array are: ");
j=arr[0];
k=j;
for (i = 1; i < 5; i++) {
if (j < arr[i])
{
if(j>k)
{
k=j;
}
j=arr[i];
}
}
Console.WriteLine("First Greatest element: "+ j);
Console.WriteLine("Second Greatest element: "+ k);
Console.Write("\n");
}
int max = 0;
int secondmax = 0;
int[] arr = { 2, 11, 15, 1, 7, 99, 6, 85, 4 };
for (int r = 0; r < arr.Length; r++)
{
if (max < arr[r])
{
max = arr[r];
}
}
for (int r = 0; r < arr.Length; r++)
{
if (secondmax < arr[r] && arr[r] < max)
{
secondmax = arr[r];
}
}
Console.WriteLine(max);
Console.WriteLine(secondmax);
Console.Read();
Python 36>=
def sec_max(array: list) -> int:
_max_: int = max(array)
second: int = 0
for element in array:
if second < element < _max_:
second = element
else:
continue
return second
Using below code we can find out second highest number, even array contains multiple max numbers
// int[] myArray = { 25, 25, 5, 20, 50, 23, 10 };
public static int GetSecondHighestNumberForUniqueNumbers(int[] numbers)
{
int highestNumber = 0, Seconhight = 0;
List<int> numberList = new List<int>();
for (int i = 0; i < numbers.Length; i++)
{
//For loop should move forward only for unique items
if (numberList.Contains(numbers[i]))
continue;
else
numberList.Add(numbers[i]);
//find higest number
if (highestNumber < numbers[i])
{
Seconhight = highestNumber;
highestNumber = numbers[i];
} //find second highest number
else if (Seconhight < numbers[i])
{
Seconhight = numbers[i];
}
}
It's not like that your structure is a tree...It's just a simple array, right?
The best solution is to sort the array. And depending on descending or ascending, display the second or the 2nd last element respectively.
The other alternative is to use some inbuilt methods, to get the initial max. Pop that element, and then search for the max again. Don't know C#, so can't give the direct code.
You'd want to sort the numbers, then just take the second largest. Here's a snippet without any consideration of efficiency:
var numbers = new int[] { 3, 5, 1, 5, 4 };
var result=numbers.OrderByDescending(x=>x).Distinct().Skip(1).First();
This isn't too bad:
int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 };
var secondMax =
myArray.Skip(2).Aggregate(
myArray.Take(2).OrderByDescending(x => x).AsEnumerable(),
(a, x) => a.Concat(new [] { x }).OrderByDescending(y => y).Take(2))
.Skip(1)
.First();
It's fairly low on complexity as it only every sorts a maximum of three elements
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int size;
Console.WriteLine("Enter the size of array");
size = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the element of array");
int[] arr = new int[size];
for (int i = 0; i < size; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
int length = arr.Length;
Program program = new Program();
program.SeconadLargestValue(arr, length);
}
private void SeconadLargestValue(int[] arr, int length)
{
int maxValue = 0;
int secondMaxValue = 0;
for (int i = 0; i < length; i++)
{
if (arr[i] > maxValue)
{
secondMaxValue = maxValue;
maxValue = arr[i];
}
else if(arr[i] > secondMaxValue)
{
secondMaxValue = arr[i];
}
}
Console.WriteLine("First Largest number :"+maxValue);
Console.WriteLine("Second Largest number :"+secondMaxValue);
Console.ReadLine();
}
}
}
My solution below.
class Program
{
static void Main(string[] args)
{
Program pg = new Program();
Console.WriteLine("*****************************Program to Find 2nd Highest and 2nd lowest from set of values.**************************");
Console.WriteLine("Please enter the comma seperated numbers : ");
string[] val = Console.ReadLine().Split(',');
int[] inval = Array.ConvertAll(val, int.Parse); // Converts Array from one type to other in single line or Following line
// val.Select(int.Parse)
Array.Sort(inval);
Console.WriteLine("2nd Highest is : {0} \n 2nd Lowest is : {1}", pg.Return2ndHighest(inval), pg.Return2ndLowest(inval));
Console.ReadLine();
}
//Method to get the 2nd lowest and 2nd highest from list of integers ex 1000,20,-10,40,100,200,400
public int Return2ndHighest(int[] values)
{
if (values.Length >= 2)
return values[values.Length - 2];
else
return values[0];
}
public int Return2ndLowest(int[] values)
{
if (values.Length > 2)
return values[1];
else
return values[0];
}
}
I am giving solution that's in JavaScript, it takes o(n/2) complexity to find the highest and second highest number.
here is the working Fiddler Link
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];
}
}
}
Sort the array and take the second to last value?
var result = (from elements in inputElements
orderby elements descending
select elements).Distinct().Skip(1).Take(1);
return result.FirstOrDefault();
namespace FindSecondLargestNumber
{
class Program
{
static void Main(string[] args)
{
int max=0;
int smax=0;
int i;
int[] a = new int[20];
Console.WriteLine("enter the size of the array");
int n = int.Parse(Console.ReadLine());
Console.WriteLine("elements");
for (i = 0; i < n; i++)
{
a[i] = int.Parse(Console.ReadLine());
}
for (i = 0; i < n; i++)
{
if ( a[i]>max)
{
smax = max;
max= a[i];
}
else if(a[i]>smax)
{
smax=a[i];
}
}
Console.WriteLine("max:" + max);
Console.WriteLine("second max:"+smax);
Console.ReadLine();
}
}
}