Algorithms 练习2.5.19--Kendall tau距离

来源:互联网 发布:幼儿编程app 编辑:程序博客网 时间:2024/05/16 12:20

Kendall tau distance.Write a program KendallTau.javathat computes the Kendall tau distance between two permutations in linearithmic time

public class KendallTau {    // return Kendall tau distance between two permutations    public static long distance(int[] a, int[] b) {        if (a.length != b.length) {            throw new IllegalArgumentException("Array dimensions disagree");        }        int n = a.length;        int[] ainv = new int[n];        for (int i = 0; i < n; i++)            ainv[a[i]] = i;//将a[]中元素和下标交换得ainv[]        Integer[] bnew = new Integer[n];        for (int i = 0; i < n; i++)            bnew[i] = ainv[b[i]];//将b[]中元素对应的a[]中元素的下标给bnew[],构成一个双下标数组bnew[],该数组下标为b[]的下标,该数组元素为a[]的下标        return Inversions.count(bnew);//计算bnew中的逆序数的个数即为逆序对数    }    // return a random permutation of size n    public static int[] permutation(int n) {        int[] a = new int[n];        for (int i = 0; i < n; i++)            a[i] = i;        StdRandom.shuffle(a);        return a;    }    public static void main(String[] args) {        // two random permutation of size n        int n = Integer.parseInt(args[0]);        int[] a = KendallTau.permutation(n);        int[] b = KendallTau.permutation(n);        // print initial permutation        for (int i = 0; i < n; i++)            StdOut.println(a[i] + " " + b[i]);        StdOut.println();        StdOut.println("inversions = " + KendallTau.distance(a, b));    }}


原创粉丝点击