In: Computer Science
Write a Python module that must satisfy the following-
Define a function named rinsert. This function will accept two arguments, the first a list of items to be sorted and the second an integer value in the range 0 to the length of the list, minus 1. This function shall insert the element corresponding to the second parameter into the presumably sorted list from position 0 to one less than the second parameter’s index.
Define a function named rinsort. This function will accept two arguments, the first a list of items to be sorted and the second an integer value in the range 0 to the length of the list, minus 1. This function shall sort the elements of the list from position 0 to the position corresponding to the second parameter, in ascending order using insertion sort. This function must be recursive.
Answer:
a.) def rinsert(item_list,val): item_list.sort() # Searching for the position for i in range(len(item_list)): if item_list[i] > val: index = i break # Inserting n in the list item_list = item_list[:i] + [val] + item_list[i:] return item_list item_list=[10,1,23,45,12,3,5,8,24,77,16] val=int(input("Enter an integer value (0 to len(item_list)-1): ")) if val not in range(0,len(item_list)-1): print("Please enter a value within the specified range") val = int(input("Enter an integer value (0 to len(item_list)-1: ")) print("Sorted List after insertion: ",rinsert(item_list,val))
Output:
b.) def rinsort(item_list,val): # base case if val <= 1: return # Sort first n-1 elements rinsort(item_list, val - 1) #Insert last element at its correct position in sorted array last = item_list[val - 1] j = val - 2 # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position while (j >= 0 and item_list[j] > last): item_list[j + 1] = item_list[j] j = j - 1 item_list[j + 1] = last return item_list item_list=[10,1,23,45,12,3,5,8,24,77,16] print("List before insertion sort: ",item_list) print("List after insertion sort: ",rinsort(item_list,len(item_list)))
Output: