Find the number of unordered pair in an array

前端 未结 5 1275
囚心锁ツ
囚心锁ツ 2021-01-05 10:18

I ran into an interesting algorithm problem:

Given an array of integer, find the number of un-ordered pairs in that array, say given {1, 3, 2}, the answer is 1 becau

5条回答
  •  太阳男子
    2021-01-05 10:39

    You can use a modified merge-sort algorithm. Merging would look something like this.

    merge(a, b):
        i = 0
        j = 0
        c = new int[a.length+b.length]
        inversions = 0
        for(k = 0 ; k < Math.min(a.length, b.length); k++)
            if(a[i] > b[j]):
                inversions++
                c[k] = b[j]
                j++
            else:
                c[k] = a[i]
                i++
        //dump the rest of the longer array in c
        return inversions
    

    Merging is done in O(n) time. Time complexity of the whole merge sort is O(n log n)

提交回复
热议问题