Move all odd positioned element to left half and even positioned to right half in-place

前端 未结 5 1660
别跟我提以往
别跟我提以往 2020-12-01 03:49

Given an array with positive and negative integers, move all the odd indexed elements to the left and even indexed elements to the right.

The difficult part of the p

5条回答
  •  青春惊慌失措
    2020-12-01 04:26

    I modified the code here to get this algorithm:

    void PartitionIndexParity(T arr[], size_t n)
    {
        using std::swap;
        for (size_t shift = 0, k; shift != n; shift += k)
        {
            k = (size_t)pow(3, ceil(log(n - shift) / log(3)) - 1) + 1;
            for (size_t i = 1; i < k; i *= 3)  // cycle-leader algorithm
            {
                size_t j = i;
                do { swap(arr[(j = j / 2 + (j % 2) * (k / 2)) + shift], arr[i + shift]); } while (j != i);
            }
    
            for (size_t b = shift / 2, m = shift, e = shift + (k - k / 2), i = m; shift != 0 && k != 0; )  // or just use std::rotate(arr, b, m, e)
            {
                swap(arr[b++], arr[i++]);
                if (b == m && i == e) { break; }
                if (b == m) { m = i; }
                else if (i == e) { i = m; }
            }
        }
    }
    

提交回复
热议问题