Optimal inversion counting on int arrays

前端 未结 3 763
难免孤独
难免孤独 2021-02-08 23:30

Today I was looking the latest exam of the local informatics olympiad and I found a interesting problem. Briefly, it asks to, given an integer array, count how many inversions i

相关标签:
3条回答
  • 2021-02-09 00:09

    The best result in the literature is an O(n √(log n)) algorithm due to Chan and Patrascu. No idea about the constant.

    0 讨论(0)
  • 2021-02-09 00:13

    If we assume the number of bits used to represent the integer is constant (say 32 or 64 bits), this can be solved in O(N) time.

    Here is an example python implementation.

    http://ideone.com/g57O87

    
    def inv_count(a, m=(1<<32)):
      if not m or not a:
          return 0
      count = 0
      ones = []
      zeros = []
      for n in a:
        if n & m:
          ones.append(n & ~m)
        else:
          count += len(ones)
          zeros.append(n & ~m)
      m /= 2
      return count + inv_count(ones, m) + inv_count(zeros, m)

    print inv_count([1, 2, 3, 4, 5]) print inv_count([5, 4, 3, 2, 1])

    We are able to achieve less than O(N x Log(N)) time complexity, as we are using idea behind a non-comparative sorting algorithm, radix sort, to get the count.

    0 讨论(0)
  • 2021-02-09 00:30

    O(n log n) is the best as far as I know.

    A detailed explanation was given here:

    http://www.geeksforgeeks.org/counting-inversions/

    0 讨论(0)
提交回复
热议问题