关于按排序进行排列的问题

时间:2010-06-01 10:45:34

标签: java algorithm

在“算法导论”第二版中,存在以下问题:

假设我们有一些数组:

int a[] = {1,2,3,4}

和一些随机优先级数组:

P = {36,3,97,19}

目标是使用此优先级数组随机置换数组a

这是伪代码:

PERMUTE-BY-SORTING (A)
1 n ← length[A]
2 for i ← 1 to n
3      do P[i] = RANDOM (1, n 3)
4 sort A, using P as sort keys
5 return A

结果应该是置换数组:

B={2, 4, 1, 3};

我写了这段代码:

import java.util.*;

public class Permute {

    public static void main (String[] args) {
        Random r = new Random();
        int a[] = new int[] {1,2,3,4};
        int n = a.length;
        int b[] = new int[a.length];
        int p[] = new int[a.length];
        for (int i=0; i<p.length; i++) {
            p[i] = r.nextInt(n*n*n) + 1;
        }

        // for (int i=0;i<p.length;i++){
        // System.out.println(p[i]);
        //}
    }
}

如何继续?

1 个答案:

答案 0 :(得分:3)

我不确定你遇到麻烦的部分,但基本上就是这样:

int[] a = {  1,  2,  3,  4 };
int[] p = { 36,  3, 97, 19 };

但是你考虑一下,基本上我们想把这两个列表的元素“压缩”在一起。所以在抽象层面,我们有以下内容:

Pair<int,int> zipped = { ( 1,36), ( 2, 3), ( 3,97), ( 4,19) };

现在我们按zipped中的第二个值对Pair进行排序。无论排序算法如何工作;这并不重要。

zipped = { ( 2, 3), ( 4,19), ( 1,36), ( 3,97) };

然后我们解压缩对以获得置换a

a = {  2,  4,  1,  3 };
p = {  3, 19, 36, 97 };

如何实施

zip-into - Pair - 然后解压缩工作正常。否则,您可以修改排序算法,以便每当它将p[i]的元素移动到p[j]时,它也会将a[i]移动到a[j]以保持两个数组“同步”


Java代码段

在以下代码段中,priorities数组已硬编码为上述值。你已经想出了如何用随机数来播种它。

import java.util.*;

public class PermuteBySorting {
    public static void main(String[] args) {
        class PrioritizedValue<T> implements Comparable<PrioritizedValue<T>> {
            final T value;
            final int priority;
            PrioritizedValue(T value, int priority) {
                this.value = value;
                this.priority = priority;
            }
            @Override public int compareTo(PrioritizedValue other) {
                return Integer.valueOf(this.priority).compareTo(other.priority);
            }           
        }
        int[] nums = { 1, 2, 3, 4 };
        int[] priorities = { 36, 3, 97, 19 };
        final int N = nums.length;
        List<PrioritizedValue<Integer>> list =
            new ArrayList<PrioritizedValue<Integer>>(N);
        for (int i = 0; i < N; i++) {
            list.add(new PrioritizedValue<Integer>(nums[i], priorities[i]));
        }
        Collections.sort(list);
        int[] permuted = new int[N];
        for (int i = 0; i < N; i++) {
            permuted[i] = list.get(i).value;
        }
        System.out.println(Arrays.toString(permuted));
        // prints "[2, 4, 1, 3]"
    }
}