Array Data Structure

How Array Works

An array is a linear data structure that stores elements in contiguous memory locations. The elements can be accessed directly by their index. Arrays in most programming languages have a fixed size, but dynamic arrays (like the one simulated here) can grow or shrink as needed.

Key operations:

  • Add: Appends an element to the end of the array
  • Insert: Adds an element at a specified index, shifting subsequent elements
  • Remove: Deletes an element at a specified index, shifting subsequent elements
  • Update: Changes the value of an element at a specified index

Time complexities:

  • Access: O(1)
  • Search: O(n)
  • Insertion: O(n) (worst case, when inserting at the beginning)
  • Deletion: O(n) (worst case, when deleting from the beginning)

class Array:
    data
    size

    function get(index):
        if index < 0 or index >= size:
            return null
        return data[index]

    function set(index, value):
        if index < 0 or index >= size:
            return false
        data[index] = value
        visualize()
        return true

    function insert(index, value):
        if index < 0 or index > size:
            return false
        for i from size to index + 1:
            data[i] = data[i - 1]
        data[index] = value
        size++
        visualize()
        return true

    function remove(index):
        if index < 0 or index >= size:
            return null
        value = data[index]
        for i from index to size - 2:
            data[i] = data[i + 1]
        size--
        visualize()
        return value