Answered step by step
Verified Expert Solution
Question
1 Approved Answer
The script has four steps: Read a list of integers ( no duplicates ) . Output the numbers in the list. Perform an insertion sort
The script has four steps:
Read a list of integers no duplicates
Output the numbers in the list.
Perform an insertion sort on the list.
Output the number of comparisons and swaps performed during the insertion sort.
Steps and are provided in the script.
Implement step based on the insertion sort algorithm in the book. Modify insertionsort to:
Count the number of comparisons performed.
Count the number of swaps performed.
Output the list during each iteration of the outside loop.
Implement step at the end of the script.
Hints: In order to count comparisons and swaps, modify the while loop in insertionsort Use global variables for comparisons and swaps.
The script includes three helper functions:
readnums # Read and return a list of integers.
printnumsnums # Output the numbers in nums
swapnums n m # Exchange numsn and numsm
Ex: When the input is:
the output is:
comparisons:
swaps:
I keep on getting an error on my program, please help in python: def readnums:
Read numbers from input and return them as a list of integers."""
return intnum for num in inputsplit
def printnumsnums:
Output numbers, separating each item by a space; no space or newline before the first number or after the last."""
printjoinstrn for n in nums
def swapnums n m:
Exchange numsn and numsm
numsn numsm numsm numsn
def insertionsortnumbers:
Sort the list 'numbers' using insertion sort, counting comparisons and swaps, and printing the list at each outer loop iteration."""
global comparisons, swaps
comparisons
swaps
for i in range lennumbers:
j i
# Insert numbersi into the sorted part, stopping once numbersi is in the correct position
while j and numbersj numbersj :
comparisons
swapnumbers j j
swaps
j
if j :
comparisons # Count the comparison where the while loop condition fails
printnumsnumbers
print # Newline for clarity
if namemain:
# Step : Read numbers into a list
numbers readnums
# Step : Output the numbers list
printnumsnumbers
print
# Print a newline for separation before sorting begins
# Step : Sort the numbers list
insertionsortnumbers
# Step : Output the number of comparisons and swaps performed
printf
comparisons: comparisons
printfswaps: swaps Output is nearly correct, but whitespace differs. See highlights below.
Special character legend
Input
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started