I am trying to write the insertion sort algorithm ( without the help of the solution in the book) and so far came up with this algorithm, when I matched it with the solution, it looks different. This is the code I wrote:
JavaScript
x
12
12
1
def insertSor(n):
2
key = 0
3
while key < len(n):
4
for j in range(len(n)-1):
5
if n[j] > n[j+1]:
6
n[j], n[j+1] = n[j+1], n[j]
7
key = key+1
8
return n
9
10
11
print(insertSor([2, 1, 0, 8, 9, 5]))
12
Is this code still valid as an insertion sort?
Algo in the book:
JavaScript
1
10
10
1
for j = 2 to A.length
2
key = A[j]
3
i=j-1
4
5
while i > 0 and A[i]>key
6
A[i+1]=A[i]
7
i = i - 1
8
A[i+1]=key
9
10
Advertisement
Answer
Looks like a bubble sort to me