1 Jan 2024

Arrays

What is an array?

An array is a data structure that stores a collection of elements. Each element in the array is assigned a unique index (starting from 0) that represents its position in the collection. Array are stored in contiguous memory locations.

Array

Arrays allow random access to the elements in the collection, meaning that we can use the index to directly access the elements in the array. This means that the time complexity for accessing an element in an array is O(1). However, for other operations such as insertion and deletion, the time complexity is O(n) because we need to shift the elements in the array to fill in the gap created by the insertion or deletion.

Animarion on P5js

Actions:

Value
Idx
Idx Value

Actions Queue:

    Implementation of an array

    Arrays can be implemented in different ways. In this section, we will look at how arrays are implemented in C, Python and Javascript.

    C

    #include <stdio.h>
    
    int main() {
        // Declare an array of size 5
        int arr[5];
    
        // Initialize the array
        arr[0] = 1;
        arr[1] = 2;
        arr[2] = 3;
        arr[3] = 4;
        arr[4] = 5;
    
        // Print the array
        for (int i = 0; i < 5; i++) {
            printf("%d ", arr[i]);
        }
        printf("\n");
    
        return 0;
    }
    

    Python

    # Declare an array of size 5
    arr = [i for i in range(1, 6)]
    
    # Print the array
    str_arr = [str(i) for i in arr]
    text = " ".join(str_arr)
    print(text)
    

    Javascript

    In javascript, arrays are implemented as objects. so we can't assure that the elements in the array are stored in contiguous memory locations.

    // Declare an array of size 5
    const arr = [1, 2, 3, 4, 5];
    
    // Print the array
    console.log(arr.join(" "));
    
    © 2019 Jsuarez.Dev