# Finding the complexity of a recursive method

An assignment question asks me to find the complexity of a [tail] recursive algorithm, copied below. While I understand all the complexity specifics, for example that the while loop's complexity is $n-1$ and the complexity of setting $j$ to $0$ is 1, I don't understand how I could trace the code recursively, that is within itsel - it's too hard to keep track of.

What I tried doing, is turning the algorithm into an iterative one, by simply putting all the code into a big while loop and thus avoiding the recursive call. But I'm not sure if this affects the complexity of the original algorithm.

Algorithm MyAlgorithm(A, n)
Input: Array of integer containing n elements
Output: Possibly modified Array A
done ← true
j ← 0
while j ≤ n - 2 do {
if A[j] > A[j + 1] then {
swap(A[j], A[j + 1])
done:= false
}
j ← j + 1
end while
j ← n - 1
while j ≥ 1 do
if A[j] < A[j - 1] then
swap(A[j - 1], A[j])
done:= false
j ← j - 1
end while
if ¬ done
MyAlgorithm(A, n)
else
return A

• I wrote the code in Java and tried both options (recursive and iterative) and they are indeed identical. However I'm still hoping to find out if there's a way to determine complexity exclusively using recursive method. – CodyBugstein Jan 31 '13 at 17:18

You have to analyze the circumstances in which your algorithm makes a recursive call. That is, when is not done true? Well, your it's true whenever your algorithm is required to make a swap in one of its passes over the array (one of the while loops). To analyze the total worst case running time, determine the maximum number of recursive calls, and add up the total work in each of these calls. In some recursive algorithms, the amount of work in each recursive call might be different. Is that the case in your algorithm?
Hint 2: Try to work out what the series of swaps do when taken to completion. For example, what happens when the two while loops are run on the following array: $\{4, 2, 5, 6, 1, 3\}$. After the first while loop, is some part of the array sorted? What after the second loop? What after the function is recursively called again?