Skip to content

Commit 72f86f2

Browse files
authored
Update InsertionSort.py
1 parent ac59b42 commit 72f86f2

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

InsertionSort.py

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,27 @@
11
import random
22
a=[]
33
n=int(input())
4+
# Generating 200 random numbers to sort
45
for i in range (n):
56
a.append(random.randint(0,200))
6-
for i in range(1,n):
7-
key=a[i]
8-
j=i-1
7+
8+
9+
# Iterate from the second element to the last element in the list
10+
for i in range(1, n):
11+
# Store the current element in the variable 'key'
12+
key = a[i]
913

10-
while j>=0 and key<a[j]:
11-
a[j],a[j+1]=a[j+1],a[j]
12-
j=j-1
14+
# Set the initial value for the comparison index 'j'
15+
j = i - 1
1316

14-
print(a)
17+
# Compare 'key' with elements before it and shift them to the right
18+
# until the correct position for 'key' is found
19+
while j >= 0 and key < a[j]:
20+
# Swap elements a[j] and a[j+1]
21+
a[j], a[j+1] = a[j+1], a[j]
22+
23+
# Decrement 'j' to compare 'key' with the previous element
24+
j = j - 1
25+
26+
# Print the sorted list
27+
print(a)

0 commit comments

Comments
 (0)