Question: Programming Project: write a function count _ inversions ( input _ list ) : that takes in a list as input, and returns the number
Programming Project: write a functioncountinversionsinputlist:that takes in a list as input, and returns the number of inversions. An inversion in inputList is a pair of elements x and y of the list such that x appears before y in inputList, but x y
Use base code given and do not delete any of the code:
def mergeandcountarr left, mid, right:
# Initialize inversion count to
invcount
# Create temporary arrays to hold the values of the left and right halves of the original array.
# Initialize counters and indices for merging.
# Merge the two halves:
# a Compare elements from the left and right halves.
# b If an element in the left half is greater than an element in the right half, increment the inversion count.
# c Copy the smaller element to the original array.
# Copy any remaining elements from the left and right temporary arrays back to the original array.
# Return the inversion count.
# YOUR CODE HERE Steps above are to help you implement the function
return invcount
def mergesortandcountarr left, right:
# Initialize inversion count to
invcount
# If the left index is less than the right index:
# a Calculate the middle index.
# b Recursively call mergesortandcount for the left half of the array.
# c Recursively call mergesortandcount for the right half of the array.
# d Call mergeandcount to merge the two halves and count the inversions between them.
# e Accumulate the inversion counts from the above steps.
# Return the total inversion count.
# YOUR CODE HERE Steps above are to help you implement the function
return invcount
# Do not change the function name
def countinversionsinputlist:
# Create a copy of the input list to avoid modifying the original list.
arr inputlist.copy
# Call mergesortandcount with the copied array, starting indices and ending index length of array
# Return the total inversion count.
# YOUR CODE HERE Steps above are to help you implement the function
return mergesortandcountarr lenarr
# Example usage:
if namemain:
inputlist
printcountinversionsinputlist # Output:
inputlist
printcountinversionsinputlist # Output:
inputlist
printcountinversionsinputlist # Output:
inputlist
printcountinversionsinputlist # Output:
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
