An equilibrium index of an array is any index of that array and the sum of the lower indexes value is equal to the sum of the higher indexes value. That means if "i" is called the equilibrium index of array arr, then i should be 0 =< i =<arr.Length and arr[0]+arr[1]+.....+arr[i-1] = arr[i+1]+arr[i+2]+....+arr[arr.Length-1].
For example we have an array arr with 6 elements and if equilibrium index of that array is 3 means arra[0]+arr[1]+arr[2] = arr[4] + arr[5].
Today we discuss about how to write a method in a C# to find out equilibrium index of an array.
To get the equilibrium index of an array
Implement the above logic as shown below in C#.
using System;
namespace CSharpEquilibriumIndex
{
class Program
{
static void Main(string[] args)
{
int[] arr = { 4, 8, 1, 2, 3, 7 };
Console.WriteLine("The Equilibrium index of given Array is {0}", GetEquilibrium(arr));
Console.ReadLine();
}
static int GetEquilibrium(int[] arr)
{
int iLength = arr.Length;
int iSum = 0, iLeftsum = 0, iEquiIndex = -1;
for (int i = 0; i < iLength; i++)
iSum += arr[i];
for (int i = 0; i < iLength; i++)
{
iSum = iSum - arr[i];
if (iLeftsum == iSum)
{
iEquiIndex = i;
break;
}
iLeftsum = iLeftsum + arr[i];
}
return iEquiIndex;
}
}
}
Run the above program and the output is as shown below.