Before discussing the implementation, let's explain what this function does: it does not sort the entire array A
, but only its initial n
elements. You can pass the length of the array for n
to sort the whole thing, but the fact that you pass the length separately is essential to understanding the rest of the answer.
I don't understand why we have to call the function again if n > 1
.
Perhaps a better way to explain the meaning of this condition would be that we do not call this function again when n
is one or less. This is called the base case of recursive algorithm, i.e. the case when you don't have to do anything. In case of sorting it means that an array of only one element is already sorted.
Why do we input (n-1)
when we call the function again?
Since n
is the number of elements that we need to sort, We pass n-1
to sort the front of the array. Once the function returns, we know that the portion A[1..n-1]
is already sorted. All we need to do is to move A[n]
to its right place. We do that in the DOWHILE
loop that follows: we go backward one element at a time, moving elements that are bigger than A[n]
to the right. Once the loop is over, we place A[n]
to its new place. Now the range A[1..n]
is sorted.
How does recursion in general work?
The function has two cases - the trivial base case, when everything is done, and a reduction step, when you use recursive invocation to solve a simpler problem, and then use the results of the simpler solution to construct your final solution.
once we call the function again, do we ignore the code from line 4 onwards, and jump straight into the second call?
No, once the function returns, we continue where we left. In your case, the function waits for the A[1..n-1]
range to be sorted before placing A[n]
to the right place.