python - Significant Inversions in an array -


I am working on the problem of homework to find the number of significant inversions in the integers array. The "critical inverse" is defined as follows:

A serial [a 0 , a 1 , one The important inverse is 2 , ..., a n ] is where a i 2 a J some i . Therefore for example one = [4,5,2,1,3] has 3 significant inversions, because this permutation a 0 > 2 a < Sub> 3 , a 1 2 a 2 a 1 2 a 3 .

To solve o (n log n) complexity is required, it requires the use of the partition and the approach is conquered. I chose to implement a solution based on merge sort. Def countInversions (list): if (len (list) & lt; = 1): return list, 0 and: (= [middle:]) results:

, C = merge and calculation (left, right) return result, (A + B + C)

However, I'm having trouble with the merge and counting method, especially the important inverse Calculating the Number I customize my code with the count of the normal number of inversions.

  def merge and cant (left, right): result = [] calculation = 0 i, j = 0,0 while (i  

then print (countInversions ([4,5] , 2,1,3])) 3 want to return E. However, it returns 1 return.

I am looking for some guidance on my merge and calculation method. Final implementation:

  def countInversions (list): if (lane (list)  

  1. When you got left [i] left & gt; 2 * right [ I] You want to conclude that all the values ​​in are more than [i:] 2 * right [i] and you will be Lane (left (I)) Should increase your calculation is similar to that lane -i (left). (You are just adding 1, your values ​​are very low)

  2. You need to split your merge pass into two phases, one to calculate the important derivatives To do this, and to produce a sorted output array. (In normal countdown, these two will move i and j at one point, so it can be added, but this is not right for your case.)

< P> Fixed code:

  def merge and calculation (left, right): result = [] calculation = 0 I, j = 0,0 while (i & lt; lenan (left) and J & lt; lane (right): if (left [i] & gt; 2 * right [j]): calculation + = lane (left) -j + = 1 other: i + = 1 i, j = 0 , 0 while (i & lt; len (left) and j & lt; len (true)): if (left [i]  

Comments

Popular posts from this blog

apache - 504 Gateway Time-out The server didn't respond in time. How to fix it? -

c# - .net WebSocket: CloseOutputAsync vs CloseAsync -

c++ - How to properly scale qgroupbox title with stylesheet for high resolution display? -