Is it possible to rearrange an array in place in O(N)?

后端 未结 9 1222
既然无缘
既然无缘 2020-12-24 14:17

If I have a size N array of objects, and I have an array of unique numbers in the range 1...N, is there any algorithm to rearrange the object array in-place in the or

9条回答
  •  心在旅途
    2020-12-24 14:56

    I think this should do:

    static  void arrange(T[] data, int[] p) {
        boolean[] done = new boolean[p.length];        
        for (int i = 0; i < p.length; i++) {
            if (!done[i]) {
                T t = data[i];
                for (int j = i;;) {
                    done[j] = true;
    
                    if (p[j] != i) {
                        data[j] = data[p[j]];
                        j = p[j];
                    } else {
                        data[j] = t;
                        break;
                    }
                }                
            }
        }
    }
    

    Note: This is Java. If you do this in a language without garbage collection, be sure to delete done.

    If you care about space, you can use a BitSet for done. I assume you can afford an additional bit per element because you seem willing to work with a permutation array, which is several times that size.

    This algorithm copies instances of T n + k times, where k is the number of cycles in the permutation. You can reduce this to the optimal number of copies by skipping those i where p[i] = i.

提交回复
热议问题