Introduction to Arrays

What is an Array?

An array is a data structure that stores a fixed-size sequence of elements of the same type. It provides random access to elements based on their index. Arrays have a contiguous block of memory where elements are stored, and each element is accessed using its index.

Key Points about Arrays : 

Indexing: Elements in an array are accessed using their index. The index starts from 0 for the first element and goes up to the size of the array minus one.

Fixed Size: Arrays have a fixed size that is determined at the time of creation. Once an array is created, its size remains constant.

Contiguous Memory Allocation: Elements in an array are stored in consecutive memory locations, allowing for efficient access and traversal of the elements.

Homogeneous Elements: Arrays store elements of the same type. For example, an integer array can only store integer values, and a string array can only store string values.

Insertion and Deletion: In an array, the size is fixed, so inserting or deleting an element may require shifting the other elements to accommodate the change. This operation can be costly, especially if it involves inserting or deleting elements from the beginning or middle of the array.

Array Implementation

In Python, arrays are commonly implemented using lists, which are a built-in data type. The syntax for creating an array-like structure using lists in Python is as follows:

Syntax :- array_name = [element1, element2, element3, ...]

Examples:

# Array of integers

numbers = [1, 2, 3, 4, 5]

# Array of strings

fruits = ["apple", "banana", "cherry"]

# Array of mixed data types

mixed = [1, "hello", 3.14, True] // Python is dynamically typed language

NOTE :  In some statically typed programming languages, such as C, Java, or C++, arrays typically require all elements to have the same data type. Mixing different data types within the same array is not allowed.

For example,in Java, arrays are homogeneous, meaning all elements must have the same type. Here's an example in Java:

int[] numbers = {1, 2, 3, 4, 5};  // Array of integers

char[] characters = {'a', 'b', 'c'};  // Array of characters

// Incorrect usage: Mixing data types in an array

Object[] mixed = {1, "hello", 3.14};  // This would compile, but it is not recommended due to mixing types

It's important to note that Python is a dynamically typed language, which allows for more flexibility with data types. Python lists can store elements of different data types without restrictions. However, in statically typed languages, like C or Java, arrays typically have stricter rules and require consistent data types for all elements.

Array Operations(Insertion, Deletion and Search)

Arrays can be implemented in various programming languages. Here's a theoretical implementation in Python:

class Array:

    def __init__(self, size):

        self.size = size

        self.arr = [None] * size

    def get(self, index):

        if 0 <= index < self.size:

            return self.arr[index]

        else:

            raise IndexError("Index out of range")

    def set(self, index, value):

        if 0 <= index < self.size:

            self.arr[index] = value

        else:

            raise IndexError("Index out of range")

Operations:

Insertion: Inserting an element in an array requires shifting the existing elements to make space for the new element. The complexity of insertion depends on the position where the element is being inserted. Here's an example of inserting an element at the end of the array:

def insert(self, value):

    if self.size < len(self.arr):

        self.arr[self.size] = value

        self.size += 1

    else:

        raise IndexError("Array is full")

Deletion: Deleting an element from an array involves shifting the subsequent elements to fill the gap left by the deleted element. Here's an example of deleting an element at a specific index:

def delete(self, index):

    if 0 <= index < self.size:

        for i in range(index, self.size - 1):

            self.arr[i] = self.arr[i + 1]

        self.size -= 1

    else:

        raise IndexError("Index out of range")

Searching: Searching for an element in an array involves iterating over the elements and comparing each element with the target value. Here's an example of linear searching:

def search(self, value):

    for i in range(self.size):

        if self.arr[i] == value:

            return i

    return -1  # Value not found

Here's an example usage of the Array class:

my_array = Array(5)  # Create an array of size 5


my_array.insert(0, 10)  # Insert 10 at index 0

my_array.insert(1, 20)  # Insert 20 at index 1

my_array.insert(2, 30)  # Insert 30 at index 2


print(my_array.get(1))  # Output: 20


my_array.delete(1)  # Delete element at index 1


print(my_array.search(30))  # Output: 1


my_array.set(0, 5)  # Set value 5 at index 0


print(my_array.get(0))  # Output: 5