HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavaMinor

Find maximum difference between values in an array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
maximumarraydifferencebetweenfindvalues

Problem

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[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?

Solution

What does this algorithm do? It finds the smallest and greatest number in an array and creates the difference of them.

Nope.

Consider {5, 2, 1}. The pseudo code returns 5 - 1 = 4 which happens to be the difference between the smallest and the largest value.

Now consider {1, 2, 5}. The pseudo code computes 1 - 2, 1 - 5, 2 - 5 and never updates x because all these values are < 0; the pseudo code then returns x, which is still 0. The difference between the largest and the smallest value, however, is still 5 - 1 = 4.

Context

StackExchange Code Review Q#127151, answer score: 9

Revisions (0)

No revisions yet.