Least difference between any two elements of an integer array in C#

Find the least difference between any two elements of an integer array.

I/P: {1000, 1003, 0, 11, 21 }

O/P: 3

class Least_Difference_Elements_In_Array
{
static void Main(string[] args)
{
int[] arr = { 1000, 1003, 0, 11, 21 };
if (arr.Length < 2)
{
Console.WriteLine(“Invalid array”);
}
else
{
int temp = int.MaxValue;
for (int i = 0; i < arr.Length; ++i)
{
for (int j = 0; j < arr.Length && j != i; ++j)
{
if (temp > Math.Abs(arr[i] – arr[j]))
{
temp = Math.Abs(arr[i] – arr[j]);
}
}
}
Console.WriteLine(“Least difference is: {0}”, temp);
}
Console.ReadKey();
}
}

Advertisements

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