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