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

后端 未结 9 1226
既然无缘
既然无缘 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 15:03

    The approach is to follow the "permutation cycles" of the permutation, rather than indexing the array left-to-right. But since you do have to begin somewhere, everytime a new permutation cycle is needed, the search for unpermuted elements is left-to-right:

    // Pseudo-code
    N : integer, N > 0 // N is the number of elements
    swaps : integer [0..N]
    data[N] : array of object
    permute[N] : array of integer [-1..N]  denoting permutation (used element is -1)
    next_scan_start : integer;
    next_scan_start = 0;
    while (swaps < N ) { // Search for the next index that is not-yet-permtued. for (idx_cycle_search = next_scan_start; idx_cycle_search < N; ++ idx_cycle_search) if (permute[idx_cycle_search] >= 0) break;
    next_scan_start = idx_cycle_search + 1;
    // This is a provable invariant. In short, number of non-negative // elements in permute[] equals (N - swaps) assert( idx_cycle_search < N );
    // Completely permute one permutation cycle, 'following the // permutation cycle's trail' This is O(N) while (permute[idx_cycle_search] >= 0) { swap( data[idx_cycle_search], data[permute[idx_cycle_search] ) swaps ++; old_idx = idx_cycle_search; idx_cycle_search = permute[idx_cycle_search]; permute[old_idx] = -1; // Also '= -idx_cycle_search -1' could be used rather than '-1' // and would allow reversal of these changes to permute[] array } }

提交回复
热议问题