Solution: Inversion Count in a List
This lesson explains how to calculate inversion count in a divide and conquer paradigm.
We'll cover the following...
Solution: 1
The naive solution to this problem would be to:
- Pick an element from the list
- Compare it with all elements to its right
- If the element on the right is smaller, increment the inversion count
def inversion_count(lst):"""Function to find Inversion Count:param lst: List of integers:return: The inversion count of the list"""size = len(lst)inv_count = 0 # variable to store inversion countfor curr in range(size - 1):for right in range(curr + 1, size):if lst[curr] > lst[right]:inv_count += 1return inv_count# Driver code to test above functionsif __name__ == '__main__':lst = [3, 2, 8, 4]result = inversion_count(lst)print("Number of inversions are", result)
Time complexity
The list is traversed once for each element in it. It runs in , thus, it is inefficient. ...
Access this course and 1400+ top-rated courses and projects.