Arrays
Array - The foundation of storing data
What is an Array?
💡An array is a linear collection of data values that are accessible at numbered indices, starting at index 0.
How The Array Is Stored In The Memory?
Contiguous Allocation:
Array elements are stored consecutively in memory, one after the other, starting from a specific memory address.
This allows for efficient random access to elements using their indices.
Memory Size:
The total memory occupied by an array is the product of the number of elements and the size of each element.
For example, an array of 10 integers (each 4 bytes) would occupy 40 bytes of memory.
Memory Allocation:
The location where an array is stored in memory depends on how it's declared:
Global or static arrays: Typically stored in a data segment, a fixed region of memory reserved for static data.
Local arrays within functions: Usually allocated on the stack, a
LIFO
(last-in, first-out) structure is used for function calls and local variables.Dynamically allocated arrays (using
malloc
in C ornew
in C++): Stored on the heap, a region of memory for dynamic memory allocation.
Accessing Elements:
The array has a base address, which points to the first element's memory location.
To access any element, the computer calculates its offset from the base address using its index.
Accessing an array element involves:
Calculating the memory address: Base address of the array + (index * size of each element)
Reading or writing data at that memory address.
Example:
Consider an integer array:
If the base address of the array is 0x1000
:
numbers[0]
is at address0x1000
(1st element)numbers[2]
is at address0x1008
(3rd element, offset by2 * 4
bytes)
Multidimensional Arrays:
Stored in row-major order (elements of each row are stored consecutively, followed by elements of the next row).
Big O Notation of Array Operations
Accessing at a given index
Updating at a given index
Inserting at the beginning
Inserting in the middle
Inserting at the end
Removing at the beginning
Removing in the middle
Removing at the end
Copying the array
Implementation of Array In JavaScript
Here's an example implementation of common array operations in JavaScript:
Creating an array:
Accessing elements:
Adding elements:
Removing elements:
Iterating over elements:
Searching for an element:
Sorting elements:
Last updated