198k views
4 votes
IN PYTHON

Modify the given insertion program (insertion.py) to display the insertion results per insertion pass (see output below). The given insertion.py program only shows the final sorted results and does not have a callable insertion function from the test program. Run the given program to verify the download is correct:

Output from the given insertion.py program:

Sorted array

2, 9, 18, 22, 37, 41, 53, 57, 79, 92

For this question, you must modify the given codes to create an insertion sort function (10 points) with a list as the argument (eg., insertion(arr) ).

Output:

Original list: [22, 79, 18, 41, 92, 2, 57, 37, 53, 9]

pass 1, with key = 79: [22, 79, 18, 41, 92, 2, 57, 37, 53, 9]

pass 2, with key = 18: [18, 22, 79, 41, 92, 2, 57, 37, 53, 9]

pass 3, with key = 41: [18, 22, 41, 79, 92, 2, 57, 37, 53, 9]

pass 4, with key = 92: [18, 22, 41, 79, 92, 2, 57, 37, 53, 9]

pass 5, with key = 2: [2, 18, 22, 41, 79, 92, 57, 37, 53, 9]

pass 6, with key = 57: [2, 18, 22, 41, 57, 79, 92, 37, 53, 9]

pass 7, with key = 37: [2, 18, 22, 37, 41, 57, 79, 92, 53, 9]

pass 8, with key = 53: [2, 18, 22, 37, 41, 53, 57, 79, 92, 9]

pass 9, with key = 9: [2, 9, 18, 22, 37, 41, 53, 57, 79, 92]

Insertion sorted: [2, 9, 18, 22, 37, 41, 53, 57, 79, 92]

1 Answer

4 votes

Final answer:

To modify the insertion program to display results per insertion pass, create an insertion function using insertion sort algorithm and iterate through the list.

Step-by-step explanation:

To modify the given insertion program to display the insertion results per insertion pass, you can create a separate function called insertion that takes a list as an argument. In this function, you can implement the insertion sort algorithm, which involves iterating through the list and inserting each element into its correct position.

Here is an example of the modified code:

def insertion(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
print(f'pass {i}, with key = {key}: {arr}')
return arr
original_list = [22, 79, 18, 41, 92, 2, 57, 37, 53, 9]
print(f'Original list: {original_list}')
sorted_list = insertion(original_list)
print(f'Insertion sorted: {sorted_list}')

This modified code will display the insertion results for each pass, showing the list after each insertion. The final sorted list will also be displayed.

User Brian De Alwis
by
8.1k points