0

I'm supposed to analyse this code and say something about its time complexity, but I am having trouble understanding what the code itself does, how does it change array a?

I also don't understand the following two operations: 1) foobar[a[i]]++; So you replace the zeros in foobar with elements of array a? But what does the ++ do?

2) a[outPos++]=1; This increments outPos first, and leaves a[0] unchanged during the whole for loop?

public static void foo(int[] a, int b) {
    int [] foobar = new int[b+1];
    for (int i = 0; i<foobar.length; i++)
        foobar[i]=0;
    for (int i = 0; i<a.length; i++)
        foobar[a[i]]++;
    int outPos = 0;
    for (int i=0; i<foobar.length; i++)
        for (int j=0; j<foobar[i]; j++)
            a[outPos++]=i;
}

As far as time complexity goes, I think it's O(n^2). The first two for loops run in constant time. But the worst case of the third nested loop seems to me that the last element in foobar is big, and then it would be quadratic?

2 Answers 2

2

It is an implementation of Counting Sort,

Where a[] stores the array to be sorted and b is the maximum integer in a[]

foobar[] is the counting array which is of size b

Let N = sizeof(a), M = b for common notation,

The first two loops:

  1. Initializing counting array to zeros O(M)
  2. Count the elements, say if there is 3 '10's in a[], foobar[10] = 3, O(N)

The tricky third loop:

  1. Outer loop, without doubt, O(M)
  2. Inner loop, you have to consider the total(maximum) # of time that j can be increased: which is Sum(foobar[]) = sizeof(a) = N, so indeed this loop, throughout whole outer loop iteration, is bound to be executed N times at most. So both loops as a whole is O(N+M), instead of intuitively O(NM)

So total complexity is: O(N) + O(M) + O(N+M) = O(N+M).

A tips if you found the third loop complexity is hard to understand, think in a way like this:

It is a 0-sum game. If some foobar[z] is large, then there is many foobar[j] = 0 which almost means skip the inner loop for such i. Otherwise, all foobar[j] will be about at average size.

It is hard to analysis per iteration of i, but it is easy to analysis the inner loop as a whole, as we know the total sum of foobar[] is a constant.

Sign up to request clarification or add additional context in comments.

Comments

0

This looks like a counting sort implementation. Considering that N (number of items) is the length of array a, and M (largest possible item) is b, its time complexity is O(N+M).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.