I am trying to create a Java program to find the common elements/ages between 2 arrays. However, I need the algorithm has to run on Big O(n log n) or Big O(log n) time complexity. This is what I came up with, any ideas on how to improve it? Am I counting of the steps of the operation correctly as well?
int [] AgeMale = {21, 19, 24, 22, 20, 23, 18}; //Program is executed 1 time
int [] AgeFemale = {17, 17, 22, 19}; //Program is executed 1 time
System.out.println("Age of male students: " + Arrays.toString(AgeMale)); //Title. Program is executed 1 time
System.out.println("Age of female students: " + Arrays.toString(AgeFemale)); //Title. Program is executed 1 time
for (int x = 0; x < AgeMale.length; x++) //Loop is executed n times, therefore, O(n).
{
for (int y = 0; y < AgeFemale.length; y++) //Loop is executed n times, therefore O(n).
{
if (AgeMale[x] == AgeFemale[y]) // Executed n * n time
{
System.out.println("The common ages are: " + AgeMale[x]); // Program is executed 1 time.
}
}
}