Problem 4: Given an array A[1...n] of n real numbers, give a divide-and-conquer style algorithm to compute the number of distinct pairs, which are ordered pairs of indices (i,j) such that i < j and A[i] < A[j], in O(n log n) time. Example:
A = [1, 19, 5, 19]
Distinct pairs: (1,2), (1,3), (1,4), (2,3), (3,4)
Count (your answer): 5
1. Algorithm:
- Divide the array A into two halves, A1 and A2.
- Recursively compute the number of distinct pairs in A1 and A2.
- Merge the two halves and count the number of distinct pairs that cross the boundary between A1 and A2.
2. Correctness:
- The algorithm correctly divides the array into two halves and recursively computes the number of distinct pairs in each half.
- When merging the two halves, we compare each element in A1 with each element in A2. If A[i] < A[j], where i is an index in A1 and j is an index in A2, then we have a distinct pair (i,j).
- By counting the number of distinct pairs in each half and the number of distinct pairs that cross the boundary, we obtain the total number of distinct pairs in the array.
3. Asymptotic running time:
- The algorithm divides the array into two halves at each step, resulting in a binary tree-like recursion.
- At each level of the recursion, we perform a merge operation, which takes O(n) time.
- The height of the recursion tree is log n, as we divide the array in half at each step.
- Therefore, the total running time of the algorithm is O(n log n).