-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathinsertion_sort.py
More file actions
29 lines (24 loc) · 797 Bytes
/
insertion_sort.py
File metadata and controls
29 lines (24 loc) · 797 Bytes
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
# A program to implement insertion sort
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1 # j = index no of sorted element
while j >=0 and key < arr[j] : # if element of unsorted list is less than sorted one, it will swap
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
n = int(input('enter number of elements : '))
arr = []
for i in range(0,n):
# to take input n no of times
element = int(input())
# to add the elements to the list
arr.append(element)
# to display the list to the user given by him/her
print(f'list you entered is {arr}')
# function is called
insertionSort(arr)
# to print the array
print ("Sorted array is:")
for i in range(len(arr)):
print (arr[i])