Problem: Given an array write an algorithm to print all the possible sub-arrays.
Example:
int [] a = {1, 2, 3}; Output: Possible subarrays – {1}, {2}, {3}, {1, 2} , {2, 3}, {1, 2, 3}
Approach:
Click here to read about the recursive solution – Print all subarrays using recursion
- Use three nested loops.
- Outer loops will decide the starting point of a sub-array, call it as startPoint.
- First inner loops will decide the group size (sub-array size). Group size starting from 1 and goes up array size. Let’s call is as grps.
- The most inner loop will actually print the sub-array by iterating the given array from startPoint and print the next grps elements.
- See the code below for more understanding.
Complete Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PrintAllSubArrays { | |
public void printSubArrays(int [] arrA){ | |
int arrSize = arrA.length; | |
//start point | |
for (int startPoint = 0; startPoint <arrSize ; startPoint++) { | |
//group sizes | |
for (int grps = startPoint; grps <=arrSize ; grps++) { | |
//if start point = 1 then | |
//grp size = 1 , print 1 | |
//grp size = 2, print 1 2 | |
//grp size = 3, print 1 2 3 ans so on | |
for (int j = startPoint ; j < grps ; j++) { | |
System.out.print(arrA[j] + " "); | |
} | |
System.out.println(); | |
} | |
} | |
} | |
public static void main(String[] args) { | |
int [] arrA = {1,2,3, 4}; | |
new PrintAllSubArrays().printSubArrays(arrA); | |
} | |
} |
Output:
1 1 2 1 2 3 1 2 3 4 2 2 3 2 3 4 3 3 4 4