The direct computation of the numerator n_c - n_d, involves two nested iterations, as characterized by the following pseudocode: numer := 0
for i := 2..N
do for j := 1..(i − 1)
do numer := numer + sign(x[i] − x[j]) × sign(y[i] − y[j])
return numer Although quick to implement, this algorithm is O(n^2) in complexity and becomes very slow on large samples. A more sophisticated algorithm built upon the
Merge Sort algorithm can be used to compute the numerator in O(n \cdot \log{n}) time. Begin by ordering your data points sorting by the first quantity, x, and secondarily (among ties in x) by the second quantity, y. With this initial ordering, y is not sorted, and the core of the algorithm consists of computing how many steps a
Bubble Sort would take to sort this initial y. An enhanced
Merge Sort algorithm, with O(n \log n) complexity, can be applied to compute the number of swaps, S(y), that would be required by a
Bubble Sort to sort y_i. Then the numerator for \tau is computed as: :n_c-n_d = n_0 - n_1 - n_2 + n_3 - 2 S(y), where n_3 is computed like n_1 and n_2, but with respect to the joint ties in x and y. A
Merge Sort partitions the data to be sorted, y into two roughly equal halves, y_\mathrm{left} and y_\mathrm{right}, then sorts each half recursively, and then merges the two sorted halves into a fully sorted vector. The number of
Bubble Sort swaps is equal to: :S(y) = S(y_\mathrm{left}) + S(y_\mathrm{right}) + M(Y_\mathrm{left},Y_\mathrm{right}) where Y_\mathrm{left} and Y_\mathrm{right} are the sorted versions of y_\mathrm{left} and y_\mathrm{right}, and M(\cdot,\cdot) characterizes the
Bubble Sort swap-equivalent for a merge operation. M(\cdot,\cdot) is computed as depicted in the following pseudo-code:
function M(L[1..n], R[1..m])
is i := 1 j := 1 nSwaps := 0
while i ≤ n
and j ≤ m
do if R[j] x and a sorted version of y. With these, the factors t_i and u_j used to compute \tau_B are easily obtained in a single linear-time pass through the sorted arrays. == Approximating Kendall rank correlation from a stream ==