Program opened below. You can scroll through the algorithm, Java code and output.
Program 48
Common Elements of Two Arrays
Question
Find the common elements of two integer arrays, remove duplicate results and display them in ascending order.
Algorithm
Step 1: Start the program and accept the size and elements of the first array.
Step 2: Accept the size and elements of the second array.
Step 3: Create a result array large enough to hold common values from the first array.
Step 4: Visit each element of the first array.
Step 5: Search the second array to determine whether the current value is common to both arrays.
Step 6: Search the result array to check whether the value has already been stored.
Step 7: Store the value only when it is common and has not already been added.
Step 8: Continue until all elements of the first array have been checked.
Step 9: Sort the stored common values in ascending order using adjacent comparisons and swapping.
Step 10: Repeat sorting passes until the common values are ordered.
Step 11: Display each common value on a separate line or report that there are no common values.
Step 12: Stop the program.
Java program
Javaimport java.util.*;
class CommonArrayElements
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Size of first array: ");
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = sc.nextInt();
}
System.out.print("Size of second array: ");
int m = sc.nextInt();
int[] b = new int[m];
for (int i = 0; i < m; i++)
{
b[i] = sc.nextInt();
}
int[] c = new int[n];
int count = 0;
for (int i = 0; i < n; i++)
{
boolean common = false, repeated = false;
for (int j = 0; j < m; j++) if (a[i] == b[j])
{
common = true;
}
for (int k = 0; k < count; k++) if (c[k] == a[i])
{
repeated = true;
}
if (common && !repeated)
{
c[count++] = a[i];
}
}
for (int i = 0; i < count - 1; i++)
{
for (int j = 0; j < count - i - 1; j++)
{
if (c[j] > c[j + 1])
{
int t = c[j];
c[j] = c[j + 1];
c[j + 1] = t;
}
}
}
System.out.println("Common elements:");
for (int i = 0; i < count; i++)
{
System.out.print(c[i] + " ");
}
if (count == 0)
{
System.out.print("None");
}
System.out.println();
}
}Sample output
Input: Array A: 4 2 7 2; Array B: 2 7 9
Output: Common elements: 2 7