Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interview Question: Replacing two arrays's place in memory

Tags:

arrays

Given two consecutive arrays, A and B. They look something like

int AandB[] = {a1,a2,...,am,b1,b2,...,bn};

You need to write a program that would switch the order of arrays A and B in the memory, so that B would appear before A. In our example, AandB should become

int AandB[] = {b1,b2,...,bn,a1,...,am};

What's the most efficient way to do that?

like image 820
Elazar Leibovich Avatar asked Jan 19 '11 14:01

Elazar Leibovich


1 Answers

Three array reverses:

(a1 a2 a3 a4 a5 b1 b2 b3)
 b3 b2 b1 a5 a4 a3 a2 a1
(b3 b2 b1)a5 a4 a3 a2 a1
 b1 b2 b3 a5 a4 a3 a2 a1
 b1 b2 b3(a5 a4 a3 a2 a1)
 b1 b2 b3 a1 a2 a3 a4 a5

Expressed using a "rev" function that takes a start and end:

rev(AandB, 0, n+m)
rev(AandB, 0, m)
rev(AandB, m, n)

For rev (omitting types, etc. for clarity):

rev(x, i, j) {
    j--; // j points to one after the subarray we're reversing
    while (i < j) {
        tmp = x[i];
        x[i] = x[j];
        x[j] = tmp;
        i++;
        j--;
    }
}
like image 83
user295691 Avatar answered Oct 04 '22 13:10

user295691