简体   繁体   中英

What's the time complexity of this method to find the number of inversions in an array (python)?

inv=0
for j in range(n):
     inv=inv+ sum((x<arr[j]) for x in arr[j:] )

For every element I am checking the number of elements smaller than it occurring after it in the array.( arr[j : ] )

It is O(n 2 ) . Here is how you can compute this:

  • for the 1 st element, you need to compare with the next n-1 elements.

  • for the 2 nd element, you need to compare with the next n-2 elements.

    ...

  • for the n th element, you need to compare with the next 0 elements.

Therefore, in total you are making (n-1) + (n-2) + ... + 1 + 0 = n(n-1) / 2 comparisons, which is quadratic in n.


More efficient approaches do exist. For example, by using a divide and conquer based strategy, you can count them in O(n log(n)) . See this nice link !

inv=0
for j in range(n):
    inv=inv+ sum((x<arr[j]) for x in arr[j:] )

Let's break this code into three parts

1: inv = 0 This will take contant time operation sat T1

2: for j in range(n): here we are running a loop for variable n

total time required now is T1 + N * f(a) here f(a) is the time taken by the body of loop. For simplicity we can remove constant factor. So complexity is N * f(a)

Now here comes the tricky part. What is f(a)

3: inv = inv + sum((x<arr[j]) for x in arr[j:] ) concentrate on sum((x < arr[j] for x in arr[j:]) sum will add all the values that are below arr[j] in

loop for x in arr[j:]

so you are left with f(a) as N , N - 1 , N - 2 up to N - N

Combining this all together you get N * (N + N - 1 + N - 2 + ... + N - N) which is (N * N - 1) / 2 that is O(N^2)

Hope you get it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM