I got two tasks to do:
1.) Create an algorithm so it detects if there are duplicates (= same numbers) in an array (the better its runtime is, the more points I get).
2.) Analyze the runtime of your algorithm.
Here is my code for the first task (I had to sort the array so the algorithm works faster / works at all. For this I used import
instead of coding it myself.):
import java.util.Arrays;
public class Dupescanner
{
public static void main(String[] args)
{
int[] A = {1, 2, 3, 4, 5, 1, 2, 8, 8};
Arrays.sort(A);
System.out.println("Following numbers are duplicates:");
for (int n = 1; n < A.length; n++)
{
if (A[n] == A[n - 1])
{
System.out.println(A[n]);
}
}
}
}
Output:
Following numbers are duplicates:
1
2
8
Is that algorithm fine? I couldn't think of anything that is faster than this one. Or maybe I mis understood the task and it's enough if you just say: true - there is / are duplicates. false - not...
For the runtime analysis, I wasn't sure but I gave it a try as well:
int[] A = {1, 2, 3, 4, 5, 1, 2, 8, 8};
costs 1
the for loop costs n and the if costs n too. Result would be n^2 + 1. Also I'm not sure if the array sort counts, I excluded it.