Home > Back-end >  Swapping sections of an array
Swapping sections of an array

Time:11-04

I was asked to make a function that swaps two sections in array.

Something like this,

array[] = {1 , 2, 5, 7, 8, a , b, c}
           |               |
sections:  First           Second

The signature is void reverse_reg(int *arr, int s, int k, int j) where arr is the array, s is the first index of the first section, k is the last index of the first section and j denotes the end of the second section, the start is k ( since indexing in C start from 0 )

So far I have something something like this,

void reverse_reg(int *arr, int s, int k, int j)
{
    for (int i = s; i < j; i  )
    {
        if (i > k / 2) /* swap the rest */
        {
            swap(&arr[i], &arr[j - i   1]); /* this is wrong */
        }
        else
        {
            swap(&arr[i], &arr[k   i   1]);
        }
    }
}

I have tested the else block and so far it swaps successfully the second section, producing,

result:
a b c 7 8 1 2 5

Though, I haven't been able to find a way to swap the second part, since the if block, produces something completely wrong (and it makes sense), which makes me think that the initial logic is wrong. Any hints?

If it helps, the way I call the function is, reverse_reg(arr, 0, 4, 8);

The resulting array should be:

result:
a b c 1 2 5 7 8

CodePudding user response:

As pointed out by @EugeneSh., a simple way is to reverse each section and then reverse the whole array. It could be as simple as:

void swap(int* i, int* j) {
    int k = *i;
    *i = *j;
    *j = k;
}

void reverse(int arr[], int len) {
    for (int i = 0; i < len / 2; i  ) {
        swap(arr   i, arr   len - i - 1);
    }
}

void reverse_reg(int* arr, int s, int k, int j) {
    // you use last index of initial section while I need index of second one
      k;
    reverse(arr   s, k - s);
    reverse(arr   k, j - k);
    reverse(arr   s, j - s);
}

CodePudding user response:

12578abc
abc12578

Assuming array is declared as unsigned char array[8];, this can be a rotate operation on 64-bit integer, we can rewrite it as:

uint64_t num = 0x01020507080a0b0c;

Using a rotate function, we can shift 'abc' to left, '12578' to the right.

uint64_t rot_left_64(uint64_t num, int n) 
{
    return (num << n) | (num >> (64 - n));
}

num = rot_left_64(num , 8 * 5);
printf("6llX\n", n);

//output
0x0A0B0C0102050708
  • Related