My task is to use the following pseudocode and improve it (make it run faster). Also I have to analyze the runtime of the given pseudocode and of my new code that i improved.
What does this algorithm do? It finds the smallest and greatest number in an array and creates the difference of them.
Pseudocode (given in task):
Input: Array Y, length n with n >= 2
Output: x (number)
x = 0
for i = 0 to n do
for j = i + 1 to n do
if x < A[i] - A[j] then
x = A[i] - A[j];
end if
end for
end for
return x;
My code, improved:
public class Improved
{
public static void main (String[] args)
{
int A[] = {1, 2, 3, 4, 5};
int min = A[0];
int max = A[0];
for (int i = 0; i < A.length; i++)
{
if (min > A[i])
{
min = A[i];
}
if (max < A[i])
{
max = A[i];
}
}
System.out.println(max - min);
}
}
The only problem I got now is counting the runtime. I think for the pseudocode, it runs in \$\mathcal{O}(n^2)\$ because of the 2 for loops. Then my code will run in \$\mathcal{O}(n)\$, since it only has 1 for loop, right? :P What would be the worst case by the way?
Y
is also not a good variable name... \$\endgroup\$Enumerable.Max(A) - Enumerable.Min(A)
? \$\endgroup\$Y
asA
in your pseudo code? \$\endgroup\$