Skip to content

Commit 7fb7965

Browse files
Merge pull request #780 from Maleehak/master
add insertion_sort algorithm
2 parents 0c0bb82 + 43e9b18 commit 7fb7965

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

insertion_sort.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
#insertion sort
2+
3+
list = [] # declaring list
4+
5+
6+
def input_list():
7+
#taking length and then values of list as input from user
8+
n = int(input("Enter number of elements in the list: ")) # taking value from user
9+
for i in range(n):
10+
temp = int(input("Enter element " + str(i + 1) + ': '))
11+
list.append( temp )
12+
13+
14+
def insertion_sort(list,n):
15+
"""
16+
sort list in assending order
17+
18+
INPUT:
19+
list=list of values to be sorted
20+
n=size of list that contains values to be sorted
21+
22+
OUTPUT:
23+
list of sorted values in assending order
24+
"""
25+
for i in range(0,n):
26+
key = list[i]
27+
j = i - 1
28+
#Swap elements witth key iff they are
29+
#greater than key
30+
while j >= 0 and list[j] > key:
31+
list[j + 1] = list[j]
32+
j = j - 1
33+
list[j + 1] = key
34+
return list
35+
36+
37+
def insertion_sort_desc(list,n):
38+
"""
39+
sort list in desending order
40+
41+
INPUT:
42+
list=list of values to be sorted
43+
n=size of list that contains values to be sorted
44+
45+
OUTPUT:
46+
list of sorted values in desending order
47+
"""
48+
for i in range(0,n):
49+
key = list[i]
50+
j = i - 1
51+
#Swap elements witth key iff they are
52+
#greater than key
53+
while j >= 0 and list[j] < key:
54+
list[j + 1] = list[j]
55+
j = j - 1
56+
list[j + 1] = key
57+
return list
58+
59+
60+
input_list()
61+
list1=insertion_sort(list,len(list))
62+
print(list1)
63+
list2=insertion_sort_desc(list,len(list))
64+
print(list2)

0 commit comments

Comments
 (0)