Data Structures: Concepts and Implementations – Part 1: Arrays

jaovitm

João Vitor

Posted on November 9, 2024

Data Structures: Concepts and Implementations – Part 1: Arrays

A Brief Introduction

Just as we store clothes in a wardrobe or tools in an appropriate box, in programming, we also need specific ways to store and organize different types of data. These ways are called data structures.

Each structure is designed to solve specific problems and organize data efficiently, whether in a simple list, a task queue, or a complex search system.

In this series of posts, we’ll explore the main data structures, understand their purposes, and see how they can make a programmer’s life easier.

Before we begin, it’s worth mentioning that the language used in this series will be C#. Although syntax may vary depending on the programming language, the core concept remains the same.

Arrays

Think of lists or arrays as an ordered line of information. In programming, arrays hold data in a precise sequence, where each item occupies a specific position called an index.

Arrays are fixed-size data structures that store elements of the same type in sequential memory locations.

Key Characteristics:

  • Homogeneity:
    All elements in an array must be of the same data type (e.g., int, float, char), allowing for efficient storage and quick access.

  • Fixed size:
    The size of an array is defined at creation and cannot be altered. To increase or decrease the number of elements, a new memory region would need to be allocated and elements copied, which is a costly operation.

  • Direct access:
    Arrays allow direct access to any element using the index, making access complexity 𝑂(1) (constant time). Array index always start at 0, meaning the first element is at index 0, the second at index 1, and so forth.

  • Contiguous allocation:
    Memory is allocated contiguously, meaning all array elements are stored adjacent to each other in memory, optimizing low-level operations.

Declaration and Usage

The standard declaration for an array follows this structure:

Array Declaration

For example, an integer (int) array of size 10 would be declared as follows:

Int array declaration

Data Manipulation

There are two basic ways to insert data into an array:

  1. At the time of declaration:

Data Manipulation

In the first example, we explicitly declare an integer array with 5 positions. Specifying more or fewer elements than the defined size (5) would result in a compilation error.

In the second line, the number of elements the array will contain is not explicitly declared. By implicitly defining the array size, its capacity is automatically set to the number of items provided during initialization.

  1. By accessing the index of the created array:

Acessing the array

Another way to add elements to an array is by using item index. In the example above, we declare a string array with size 2. We then assign values to specific array positions: the element at index 0 receives the string "Hello," while the element at index 1 receives the string "World."

Displaying Data

Just as we can set a value for an array element using its index, we can retrieve the value stored in a specific position by accessing that index.

Data Access

Array Types

Arrays can be classified as either one-dimensional or multidimensional. One-dimensional arrays are simply lists of elements, while multidimensional arrays, often called matrices, are used to represent tables or data structures with more than one dimension.

  1. One-Dimensional Arrays

One-dimensional array

  1. Multidimensional Arrays

Multidimensional array

A multidimensional array can be described as an array of arrays. This type of array is useful when we need to store and display data in a tabular format, like a table, with rows and columns.

Important Note: A single comma [,] specifies a two-dimensional array. A three-dimensional array would have two commas: int[,,], and so on.

Array Class Properties in C

Property Description
IsReadOnly Returns a boolean indicating if the array is read-only.
Length Returns the total number of items in an array across all dimensions.
Rank Returns the number of dimensions of an array. A two-dimensional array would return 2, for instance.

Array Class Methods in C

Method Description
AsReadOnly() Returns a read-only wrapper for the specified array.
BinarySearch() Searches a sorted one-dimensional array for a value using the binary search algorithm.
Clear() Sets a range of elements in an array to the default value for each element type.
Clone() Creates a shallow copy of the array.
ConstrainedCopy() Copies a range of elements from one array to another, guaranteeing all changes are undone if the copy fails.
ConvertAll() Converts an array of one type to an array of another type.
Copy() Copies a range of elements from one array to another, with type conversion and boxing as needed.
CopyTo() Copies all elements of the current one-dimensional array to the specified one-dimensional array.
CreateInstance() Initializes a new instance of the Array class.
Empty() Returns an empty array.
Equals() Determines whether the specified object is equal to the current object.
Exists() Checks if the specified array contains elements that meet the specified predicate’s conditions.
Find() Searches for an element meeting specified conditions and returns the first occurrence in the array.
FindAll() Retrieves all elements that meet the specified predicate conditions.
FindIndex() Searches for an element meeting specified conditions and returns its index in zero-based notation.
FindLast() Searches for an element meeting specified conditions and returns the last occurrence in the array.
FindLastIndex() Searches for an element meeting specified conditions and returns its last occurrence index in zero-based notation.
ForEach() Performs the specified action on each element of the specified array.
GetEnumerator() Returns an IEnumerator for the array.
GetHashCode() Serves as the default hash function.
GetLength() Gets a 32-bit integer representing the number of elements in the specified array dimension.
GetLongLength() Gets a 64-bit integer representing the number of elements in the specified array dimension.
GetLowerBound() Gets the index of the first element in the specified array dimension.
GetType() Gets the type of the current instance.
GetUpperBound() Gets the index of the last element in the specified array dimension.
GetValue() Gets the value of the specified element in the current array.
IndexOf() Searches for the specified object and returns the index of its first occurrence in a one-dimensional array.
Initialize() Initializes each element of an array value type by calling the value type’s default constructor.
LastIndexOf() Returns the index of the last occurrence of a value in a one-dimensional array.
MemberwiseClone() Creates a shallow copy of the current object.
Resize() Changes the number of elements in a one-dimensional array to the specified new size.
Reverse() Reverses the order of elements in a one-dimensional array.
SetValue() Sets the specified element in the current array to the specified value.
Sort() Sorts the elements of a one-dimensional array.
ToString() Returns a string representing the current object. (Inherited from Object)
TrueForAll() Determines if all elements in the array meet the conditions defined by the specified predicate.

Final Considerations:

In summary, arrays are a fundamental structure in programming with both advantages and disadvantages. They are particularly useful when we need to store and manage multiple variables of the same type efficiently, making them indispensable in various situations.

You’ll likely use arrays frequently throughout your development journey. Have you already used arrays in your projects? What challenges or benefits have you encountered? Share your experience in the comments!

💖 💪 🙅 🚩
jaovitm
João Vitor

Posted on November 9, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related