I have the following pseudo code for a insertion sort algorithm
INSERTION-SORT
1 for j = 2 to A.length
2 key = A[j]
3 // Insert A[j] into the sorted sequence A[1..j-1]
4 i = j -1
5 while i > 0 and A[i] > key
6 A[i+1] = A[i]
7 i = i -1
8 A[i+1] = key
I am trying to convert it into executable code written in Python
def main():
A = [5,2,4,6,1,3]
for j in range(1,len(A)):
key = A[j]
i = j - 1
while i >= 0 and A[i] > key:
A[i + 1] = A[i]
i = i - 1
A[i + 1] = key
print A[0:j+1]
return A
main()
is this a correct translation? I'm not sure if I messed something up with the indexes because it seems as though I'm not getting the end index with range. Furthermore I'm going to be testing correctness with initialization, maintenance and termination.
I added the line print A[0:j] to show initialization and maintenance but I'm not sure if it should be print A[0:j-1].
Any help is greatly appreciated!
I'm not sure if I messed something up …hard to follow not given any specification.it seems as though I'm not getting the end index with rangethere are fine manuals aboutrange()and slices. (I seem to remember loop invariant. While programming questions are off-topic here, your question may be about the semantics of Python ranges & slicing, which I'd consider border-line.) $\endgroup$