If you want to practice data structure and algorithm programs, you can go through 100+ data structure and algorithm programs.
In this post, we will see how to generate all subarrays of given array.
Problem
Print all print all subarrays of given array.
For example:
If array is {1,2,3}
then you need to print
{1}, {2}, {3}, {1,2}, {2,3}, {1,2,3}
then you need to print
{1}, {2}, {3}, {1,2}, {2,3}, {1,2,3}
Solution
If there are n elements in the array then there will be (n*n+1)/2 subarrays.
Here is a simple algorithm for it.
- We will use three loop to print subarrays.
- Outer loop will be used to get start index
- First inner loop will be used to get end index
- Second inner loop will be used to print element from start to end index.
here is simple program to print all subarrays of given array..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package org.arpit.java2blog; public class PrintSubarrayMain { public static void main(String args[]){ PrintSubarrayMain psm=new PrintSubarrayMain(); int arr[]= {1,2,3,4}; psm.printSubArray(arr); } void printSubArray(int arr[]) { int n=arr.length; for (int i=0; i <n; i++) //This loop will select start element { for (int j=i; j<n; j++) // This loop will select end element { for (int k=i; k<=j; k++) //This loop will print element from start to end { System.out.print( arr[k]+" "); } System.out.println(); } } } } |
That’s all about how to generate all subarrays of a given array
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.