in-place bit-reversed shuffle on an array

前端 未结 7 1331
后悔当初
后悔当初 2020-12-05 08:50

For a FFT function I need to permutate or shuffle the elements within an array in a bit-reversed way. That\'s a common task with FFTs because most power of two sized FFT fun

7条回答
  •  离开以前
    2020-12-05 09:36

    To swap in place with a single pass, iterate once through all elements in increasing index. Perform a swap only if the index is less-than the reversed index -- this will skip the double swap problem and also palindrome cases (elements 00000000b, 10000001b, 10100101b) which inverse to the same value and no swap is required.

    // Let data[256] be your element array 
    for (i=0; i<256; i++)
        j = bit_reverse(i);
        if (i < j)
        {
            swap(data[i],data[j]);
        }
    

    The bit_reverse() can be using Nathaneil's bit-operations trick. The bit_reverse() will be called 256 times but the swap() will be called less than 128 times.

提交回复
热议问题