One Dimensional Array Element Insert

tags: array-insert array-copy non-strict-comparison

Insert an element at a given index in an array.

Solution Outline

  1. Create a temporary array of size one more than the original array.
  2. Copy the elements at index less than the insert index to the temporary array.
  3. Skip the value for the insert index, copy the the remaining elements to the temporary array.
  4. Insert the value at the insert index in the temporary array.
  5. Change the reference of array to temporary and return it.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
def insert(array, value, index)
  n = array.size
  temp = Array.new(n+1)
  
  for i in (0..n-1)
    if i < index
      temp[i] = array[i]
    else
      temp[i+1] = array[i]
    end
  end
  
  temp[index] = value
  array = temp
  
  return array
end

array = [1,2,4,5]

p insert(array, 3, 2)