In: Computer Science
Intro to python question:
#Recall in the lesson on sorts that we had you complete
the
#Bubble and Selection sort, and we showed you Merge sort.
#We didn't show any of insertion sort, and I bet you can
#guess why.
#
#Implement insertion sort below.
#
#Name your function 'insertion'. insertion should take as
#input a list, and return as output a sorted list. Note that
#even though technically a sorting method does not have to
#return the sorted list, yours should.
#
#If you're stuck on where to start, or having trouble
#visualizing or understanding how exactly insertion sort
#works, check out this website - https://visualgo.net/sorting
#It provides a visual representation of all of the sorting
#algorithms as well as pseudocode you can base your own code
#off of.
#Write your code here!
#The code below will test your function. If your function
#works, it will print: [1, 2, 3, 4, 5].
print(insertion([5, 1, 3, 2, 4]))
Please find the code below and also attached execution output screen shot below.
Added all the comments for your understanding in each ine of the code.
#This below program is for insertion sort and function will return sorted array
# this below is the function where we implemented insertion sort logic
def insertion(input_array):
# we will start looping and we will traverse through each element from index value 1 of array (i.e index = 1 ) to the end of complete array length
# array length will be obtained by len funtcion
for each_elem in range(1, len(input_array)):
#here we are extracting the current indexed array value and storing it in current_element
current_element = input_array[each_elem]
# Now we will move those elements of input_array[0..each_elem-1], which are greater than current_element in such a way that
# to 1 position ahead of their current position which we store this index in iter_elem
#all the below code which is in while loop is for moving elements on position ahead which have values greater than current_element value
iter_elem = each_elem-1
while iter_elem >=0 and current_element < input_array[iter_elem] :
input_array[iter_elem+1] = input_array[iter_elem]
iter_elem -= 1
input_array[iter_elem+1] = current_element
#we will return now sorted array i.e input_array
return input_array
# We will use input_array where we required to sort
input_array = [5, 1, 3, 2, 4]
#you can call function insertion by below line also
#print(insertion(input_array))
#this below statement is from your problem statement
print(insertion([5, 1, 3, 2, 4]))
Screenshot: