How to find all possible subarray of an array in c# using recursion


This article outlines how to find all possible subarray of a given array. To solve the problem recursion is used in our algorithm. If we know all the subarray of a (n-1) element of array then we can easily find out the subarray for all the n elements. Language used is c#.

Following is a c# method getSubArray that returns a List of all possible subarray of mainArray. Method is using recursion in algorithm. Paramter index should be equal to the size of mainArray.



public List> getSubArray(int[] mainArray, int index)
{
List> returnArrayList = new List>();
List> returnOldList = new List>();
if (index == 1)
{
List arrayint = new List();
arrayint.Add(mainArray[0]);
returnArrayList.Add(arrayint);
return returnArrayList;
}

else
{
returnOldList = getSubArray(mainArray, index - 1);
foreach (var item in returnOldList)
{
returnArrayList.Add(item);
}

foreach (var item in returnOldList)
{
List tl = new List();
foreach (var i in item)
{
tl.Add(i);
}
tl.Add(mainArray[index - 1]);

returnArrayList.Add(tl);
}

List arrayNewint = new List();
arrayNewint.Add(mainArray[index - 1]);
returnArrayList.Add(arrayNewint);

return returnArrayList;
}
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: