One Dimensional Array Element Delete

tags: array-delete array-left-shift two-way-comparison array-copy strict-comparison

Delete an element at a given index in an array.

Solution Outline

  1. Create a temporary array of size one less than the input array.
  2. If the loop index is less than the delete index copy the elements to the temporary array.
  3. If the loop index is greater than the delete index, copy the elements one location to the left to fill in the gap for the element deleted.
  4. Change the input array reference to temporary array
  5. Return the input array
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def delete(a, index)
  temp = Array.new(a.size-1)

  for i in (0..a.size-1) 
    # Copy data in front of the index to the front of the temp array
    if i < index
      temp[i] = a[i]  
    end

    # Copy data after index to the end of the temp array
    if i > index
      temp[i-1] = a[i]
    end
  end
  
  a = temp
  
  return a
end

a = [0,1,2,3,4,5]

p delete(a, 1)