Search code examples
algorithmpseudocode

Copy all elements of a array to another array at the specified index


I want to copy all elements of an array to another at a specified location.

Eg:

Array A contains {'a', 'b', 'c', 'd'}

Array B contains {'x','y', 'z'}

Array C should now contain {'a', 'x', 'y', 'z', 'b', 'c', 'd'} when `insert-index`  is 1 (insert all B's at first index of A)

My preferred programming is in Java or in C#

pseudo-code of my try:

//Copy all the elements of the first array to the output array till the index //Copies 'a' to the output array

for(int i=0;i<insert-index;i++)
output[i] = A[i] 

//Copy all the elements of the destination array to the output array //copies 'x','y','z' to the output array

for(int i=0;i<B.Array.Length;i++)
output[i] = B[i]

//copy all the elements of the source array to the output array. //copies remaining 'b', 'c', 'd'

for(int i=0;i<A.Array.Length-index;i++)
output[i]=A[i]

The best shot at the algorithm I could give is O(n power 3)

Can any body tell me how else to approach or any pointers is greatly appreciated.

(EDIT: I know i could use Array.Copy or memcpy kind of internal functionality. But, I am just trying to learn how did they do it and also to improvise my prgm stuff.)


Solution

  • You just need to think through what the starting and ending indices need to be.
    I've included some comments below.

    // this part is straightforward
    for (int i = 0; i < insert-index; i++)
      output[i] = A[i]
    
    // we already have insert-index items in output, so continue from there
    for (int i = 0; i < B.length; i++)
      output[insert-index + i] = B[i]
    
    // we already have (B.length + insert-index) items in output,
    //   and we've already used insert-index items from A, so continue from there
    for (int i = insert-index; i < A.length; i++)
      output[B.length + i] = A[i]
    

    Since we're only touching each element of A and B once, it's O(n). But it would probably be better to say it's O(m + n), where m and n are the lengths of A and B respectively.