0

Meant to ask this here but since I forgot to mention the condition on the indices, creating a new question.

The question is given an unsorted array, find the total number of pairs of indices i, j such that i < j and arr[i] < arr[j]. Complexity should be linear or as close to it.

Community
  • 1
  • 1
Coder25
  • 311
  • 1
  • 4
  • 13
  • possible duplicate of [Counting inversions in an array](http://stackoverflow.com/questions/337664/counting-inversions-in-an-array) – NPE Dec 09 '12 at 21:48

1 Answers1

1

If the target were to find the number of pairs i < j such that arr[i] > arr[j], it would be the inversion count, that can be determined by merge-sorting the array and counting how many values each item is moved past.

Here, we can do the same, if we sort in descending order.

int pairs_count(int[] arr, int lo, int hi) {
    if (hi <= lo) return 0;
    int mid = (lo+hi)/2;
    int count = pairs_count(arr, lo, mid);
    count += pairs_count(arr, mid+1,hi);
    count += merge(arr, lo, mid, hi);
    return count;
}

int merge(int[] arr, int lo, int mid, int hi) {
    int[] scratch = new int[hi-lo+1];
    int l = lo, r = mid+1, k = 0, count = 0;
    while(l <= mid && r <= hi) {
        if (arr[r] > arr[l]) {
            scratch[k++] = arr[r++];
            count += mid-l+1;
        } else {
            scratch[k++] = arr[l++];
        }
    }
    while(l <= mid) {
        scratch[k++] = arr[l++];
    }
    while(r <= hi) {
        scratch[k++] = arr[r++];
    }
    for(k = 0; k < scratch.length; ++k) {
        arr[lo+k] = scratch[k];
    }
    retrun count;
}

call it with pairs_count(arr, 0, arr.length - 1);.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431