Algorithms in C#

After spending 9 years in IT finally I am being asked to show my skills on Algorithms. On my first interview I could solve 90% not completely. Then I thought to revive something which I had been doing throughout my career.

In this series I will be posting some commonly asked Algorithms in Interviews. Part 2 | Part 3

How to find second highest number from an array?

public int FindSecondHighest(int[] array)
{
	int first = 0;
	int second = 0;
	foreach(var item in array)
	{
		if(item > first)
		{
			second = first;
			first = item;
		}
		else if(item > second)
		{
			second = item;
		}
	}
	return second;
}

How to find second lowest number from an array?

public int FindSecondLowest(int[] array)
{
	var firstlowest = Int32.MaxValue;
	var secondLowest = Int32.MaxValue;

	if (array.Length > 2)
	{
		for (int i = 0; i < array.Length; i++)
		{
			if (array[i] < firstlowest)
			{
				secondLowest = firstlowest;
				firstlowest = array[i];
			}
			else if (array[i] < secondLowest && array[i] > firstlowest)
				secondLowest = array[i];
		}
	}
	return secondLowest;
}
Advertisements

2 thoughts on “Algorithms in C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s