Reverse & Shift

  • Reverse

In this method, we can take an auxiliary array (let's call it array B), and we copy the elements from the original array, copy them in reverse. Then, we will copy these elements back to the original array, replacing them.

This is the two pointer technique, the first pointer is at the first element of the array and the second one at the last.


void Reverse(struct Array *arr) {
  int *B;
  int i, j;

  B = (int *)malloc(arr->length * sizeof(int));

  for (i = arr->length - 1, j = 0; i >= 0; i--, j++) {
    B[j] = arr->A[i];
  }

  for (i = 0; i < arr->length; i++) {
    arr->A[i] = B[i];
  }
}

In the second method, we can scan from two ends of an array and swap the elements. We start by having two indices, i (first element) and j (last element) then increment i and decrement j. We stop when i and j has came on the same place / if i is greater than j.


void Reverse2(struct Array *arr) {
  int i, j;
  for (i = 0, j = arr->length - 1; i < j; i++, j--) {
    int temp;
    temp = arr->A[i];
    arr->A[i] = arr->A[j];
    arr->A[j] = temp;
  }
}

  • left shift

We want to shift all the elements of an array on the left hand side. We will lose the first element of the array (unless it's a rotation, then it is copied in the last location).

Rotating an array is pretty common in electronics (for example for LED boards that has a sliding text).

Exercise: coding left shift and right shift


void Lshift(struct Array *arr) {
  int i;
  int first = arr->A[0];

  for (i = 0; i < arr->length - 1; i++) {
    arr->A[i] = arr->A[i + 1];
  }

  arr->A[arr->length - 1] = first;
}

void Rshift(struct Array *arr) {
  int i;
  int last = arr->A[arr->length - 1];

  for (i = arr->length - 1; i > 0; i--) {
    arr->A[i] = arr->A[i - 1];
  }

  arr->A[0] = last;
}