Find the number of unordered pair in an array

It is possible to solve this problem in O(n log n) time using a balanced binary search tree. Here is a pseudo-code of this algorithm:

tree = an empty balanced binary search tree
answer = 0
for each element in the array:
     answer += number of the elements in the tree greater then this element
     add this element to the tree

You can use a modified version of merge sort to count the number of inversions. The trick is that while merging two sorted sub arrays you can come to know the elements which are out of place. If there are any elements in right subarray which need to go before the ones in left subarray, they are the inverted ones. I've written the code for this in python. You can check the explanation below it for better understanding. If you not able to understand merge sort I'd suggest you to revist merge sort after which this would be intuitive.

def merge_sort(l):
    if len(l) <= 1:
        return (0, l)
    else:
        mid = len(l) / 2
        count_left, ll = merge_sort(l[0:mid])
        count_right, lr = merge_sort(l[mid:])
        count_merge, merged = merge(ll, lr)
        total = count_left + count_right + count_merge
        return total, merged

def merge(left, right):
    li, ri = 0, 0
    merged = []        
    count = 0
    while li < len(left) and ri < len(right):
        if left[li] < right[ri]:
            merged.append(left[li])
            li += 1
        else:
            count += 1
            merged.append(right[ri])
            ri += 1

    if li < len(left):
        merged.extend(left[li:])
    elif ri < len(right):
        merged.extend(right[ri:])
    return count, merged

if __name__ == '__main__':
    # example 
    l = [6, 1 , 2, 3, 4, 5]
    print 'inverse pair count is %s'%merge_sort(l)[0]
  • Merge sort runs in n * log(n) time.
  • for the passed list l, merge_sort returns a tuple (in the form of (inversion_count, list)) of number of inversions and the sorted list
  • Merge step counts the number of inversions and stores it in the variable count.

If you are just looking for the number of un-ordered pair and the array is sorted in ascending order. You can use this formula n * (n - 1) / 2. Suppose your array has n elements, for example 3 in your case. It will be 3 * 2 / 2 = 3. Assuming there are no duplicate elements.