|
1 | 1 | package arrays; |
| 2 | + |
2 | 3 | /* Problem Title :-> find common elements in 3 sorted arrays */ |
3 | 4 | public class Array_Problem_19 { |
4 | 5 | // This function prints common elements in a1 |
5 | | - void findCommon(int[] a1, int[] a2, int[] a3){ |
| 6 | + void findCommon(int[] a1, int[] a2, int[] a3) { |
6 | 7 | // Initialize starting indexes for a1[], a2[] and a3[] |
7 | 8 | int i = 0, j = 0, k = 0; |
8 | 9 | // Iterate through three arrays while all arrays have elements |
9 | | - while(i < a1.length && j < a2.length && k < a3.length){ |
| 10 | + while (i < a1.length && j < a2.length && k < a3.length) { |
10 | 11 | // if x = y and y = z, print any of them and move ahead in all arrays |
11 | | - if(a1[i] >= a2[j] && a2[j] == a3[k]){ |
| 12 | + if (a1[i] >= a2[j] && a2[j] == a3[k]) { |
12 | 13 | System.out.print(a1[i] + " "); |
13 | 14 | i++; |
14 | 15 | k++; |
15 | 16 | } |
16 | | - //x < y |
17 | | - else if(a1[j] < a2[j]) i++; |
| 17 | + // x < y |
| 18 | + else if (a1[j] < a2[j]) |
| 19 | + i++; |
18 | 20 | // y < z |
19 | | - else if(a2[j] <a3[k]) j++; |
| 21 | + else if (a2[j] < a3[k]) |
| 22 | + j++; |
20 | 23 | // we reach here whem x > y and z < y, i.e., z is smallest |
21 | | - else k++; |
| 24 | + else |
| 25 | + k++; |
22 | 26 | } |
23 | 27 | } |
| 28 | + |
24 | 29 | /* Driver Code */ |
25 | | - public static void main(String[] args){ |
| 30 | + public static void main(String[] args) { |
26 | 31 |
|
27 | | - int a1[] = {1,5,10,20,40,80}; |
28 | | - int a2[] = {6,7,20,80,100}; |
29 | | - int a3[] = {3,4,15,20,30,70,80,120}; |
| 32 | + int a1[] = { 1, 5, 10, 20, 40, 80 }; |
| 33 | + int a2[] = { 6, 7, 20, 80, 100 }; |
| 34 | + int a3[] = { 3, 4, 15, 20, 30, 70, 80, 120 }; |
30 | 35 |
|
| 36 | + Array_Problem_19 ob = new Array_Problem_19(); |
31 | 37 | System.out.print("Common elements are "); |
32 | 38 | ob.findCommon(a1, a2, a3); |
33 | 39 | } |
|
0 commit comments