1

Given this algorithm in pseudocode that sorts any array, how can I formulate a loop invariant that proves its correctness using induction and how do I find its time complexity ?

Input: array A[0 . . . n − 1]

i ← 0
while i < n do
    if i = 0 or A[i] ≥ A[i − 1] then:
       i ← i + 1
    else
       swap A[i] and A[i − 1]
       i ← i − 1

Additionally I got a hint stating: Use the invariant "at the moment when the variable i gets incremented to a new value i = k for the first time, the first k elements of the array are sorted in increasing order".

Thank you in advance !

1 Answers1

1

I'll give an informal argument only.

Assume that the invariant "at the moment when the variable i gets incremented to a new value i = k for the first time, the first k elements of the array are sorted in increasing order" holds.

If we iterate from this moment, either A[k] ≥ A[k-1] and k can immediately be incremented and the k+1 first elements are sorted, or A[k] < A[k-1] and the invariant must be weakened. A proposal is to express that the sequence A[0..i-1] concatenated to A[i+1..k] remains the same sorted sequence. In the end, when A[i-1]≤A[i]≤A[i+1] the first k+1 elements will be sorted, and i will increase until that value.