0% found this document useful (0 votes)
2 views17 pages

03 EKH Arrays

The document provides a comprehensive overview of arrays, detailing their characteristics, types (one-dimensional, two-dimensional, and multi-dimensional), operations (accessing, insertion, deletion, and searching), and time complexities. It also covers traversal methods, including linear and reverse traversal, as well as algorithms for merging sorted arrays and performing matrix operations using arrays in C. Additionally, it discusses pointers and their relationship with arrays, including pointer arrays and their applications in data structures.

Uploaded by

jahinalam45
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views17 pages

03 EKH Arrays

The document provides a comprehensive overview of arrays, detailing their characteristics, types (one-dimensional, two-dimensional, and multi-dimensional), operations (accessing, insertion, deletion, and searching), and time complexities. It also covers traversal methods, including linear and reverse traversal, as well as algorithms for merging sorted arrays and performing matrix operations using arrays in C. Additionally, it discusses pointers and their relationship with arrays, including pointer arrays and their applications in data structures.

Uploaded by

jahinalam45
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Arrays

1. Introduction
A linear array is a data structure used to store a fixed-size sequential collection of elements of
the same type. It is also called a one-dimensional array.
An array is a collection of items of same data type stored at contiguous memory locations.

Characteristics of Array Data Structure:


• Homogeneous Elements: All elements within an array must be of the same data type.
• Contiguous Memory Allocation: In most programming languages, elements in an array
are stored in contiguous (adjacent) memory locations.
• Zero-Based Indexing: In many programming languages, arrays use zero-based indexing,
which means that the first element is accessed with an index of 0, the second with an
index of 1, and so on.
• Random Access: Arrays provide constant-time (O(1)) access to elements. This means
that regardless of the size of the array, it takes the same amount of time to access any
element based on its index.
Types of arrays:
• One-Dimensional Array: This is the simplest form of an array, which consists of a
single row of elements, all of the same data type. Elements in a 1D array are accessed
using a single index.

One-Dimensional Array
• Two-Dimensional Array: A two-dimensional array, often referred to as a matrix or 2D
array, is an array of arrays. It consists of rows and columns, forming a grid-like structure.
Elements in a 2D array are accessed using two indices, one for the row and one for the
column.
• Multi-Dimensional Array: Arrays can have more than two dimensions, leading to multi-
dimensional arrays. These are used when data needs to be organized in a multi-
dimensional grid.

Types of Array operations:


• Accessing Elements: Accessing a specific element in an array by its index is a constant-
time operation. It has a time complexity of O(1).
• Insertion: Appending an element to the end of an array is usually a constant-time
operation, O(1) but insertion at the beginning or any specific index takes O(n) time
because it requires shifting all of the elements.
• Deletion: Same as insertion, deleting the last element is a constant-time operation, O(1)
but deletion of element at the beginning or any specific index takes O(n) time because it
requires shifting all of the elements.
• Searching: Linear Search takes O(n) time which is useful for unsorted data and Binary
Search takes O(logn) time which is useful for sorted data.
Declaration and Initialization
In C/C++:
int arr[5]; // Declaration
int arr[5] = {10, 20, 30, 40, 50}; // Initialization
Time Complexities

Operation Time Complexity

Access O(1)

Search O(n)

Insertion O(n)

Deletion O(n)

Advantages of Linear Array


• Easy to implement and use.
• Fast access using index (random access).
Disadvantages of Linear Array
• Fixed size; can't be resized dynamically.
• Insertion and deletion are costly (due to shifting elements).

Applications of Linear Arrays


• Storing lists of items like scores, names, etc.
• Implementing other data structures such as matrices, heaps, and hash tables.
• Used in sorting and searching algorithms.

Traversal in Array
Traversal in an array refers to the process of accessing each element in the array sequentially,
typically to perform a specific operation, such as searching, sorting, or modifying the elements.
Traversing an array is essential for a wide range of tasks in programming, and the most common
methods of traversal include iterating through the array using loops like for, while, or foreach.
Efficient traversal plays a critical role in algorithms that require scanning or manipulating data.
Examples:
Input: arr[] = [10, 20, 30, 40, 50]
Output: "10 20 30 40 50 "
Explanation: Just traverse and print the numbers.
Input: arr[] = [7, 8, 9, 1, 2]
Output: "7 8 9 1 2 "
Explanation: Just traverse and print the numbers.
Input: arr[] = [100, 200, 300, 400, 500]
Output: "100 200 300 400 500 "
Explanation: Just traverse and print the numbers.
Types of Array Traversal
There are mainly two types of array traversal:
1. Linear Traversal
Linear traversal is the process of visiting each element of an array sequentially, starting from the
first element and moving to the last element. During this traversal, each element is processed
(printed, modified, or checked) one after the other, in the order they are stored in the array. This
is the most common and straightforward way of accessing the elements of an array.
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Linear Traversal: ");
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output
Linear Traversal: 1 2 3 4 5
Time Complexity: O(n)
Auxiliary Space: O(1)
2. Reverse Traversal
Reverse traversal is the process of visiting each element of an array starting from the last
element and moving towards the first element. This method is useful when you need to process
the elements of an array in reverse order. In this type of traversal, you begin from the last index
(the rightmost element) and work your way to the first index (the leftmost element).
// C Code
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Reverse Traversal: ");
for(int i = n - 1; i >= 0; i--) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output
Reverse Traversal: 5 4 3 2 1
Time Complexity: O(n)
Auxiliary Space: O(1)
Insertion:
It means insert one or more elements into the array. We can insert an element at any position in
the array like beginning, end or at any given indexed position.

Upward and Downward of the elements


1. First of all, we have to check that whether there is a room(space) available or not.
2. Where the element to insert(as mentioned like begin, end or at any given index).
3. If we insert an element in the middle location then we first move the last element into the
next location(downward) and like wise we shift the elements till the space is obtain to
insert new element.

Algorithm/Pseudo code for insertion:


Insert(LA, N, K, ITEM) where
LA = Linear array
N = Number of elements
K = the position where element to insert
ITEM = the value to insert in the position K
Step 1: [Initialise counter]
Set j = N;
Step 2: Repeat steps 3 and 4 while j>=4
Step 3: [Move jth element downward]
Set LA[j+1] = LA[j]
Step 4: [Decrease counter]
Set j=j-1
[End of Step 2 loop]
Step 5: [Insert element]
Set LA[K] = ITEM
Step 6: [Reset N]
Set N = N+1
Step 7: Exit
Deletion:
Delete an element from a particular location. When we want to delete the last element in the
array, we simple decrease the length of an array but if we want to delete the middle element into
the array then:
1. First we have to find the position of the element.
2. Move the elements to upward(see the attached image above).
Algorithm/Pseudo code for Deletion:
Delete(LA, N, K, ITEM) where
LA = Linear array
N = Number of elements
K = the position where element to delete
ITEM = the element in the position K
Step 1: Set ITEM = LA[K]
Step 2: Repeat for J = K to N-1
[Move 'J+1' element to upward]
set LA[J] = LA[J+1]
[End of loop]
Step 3: Rest the number 'N' of LA.
Set N = N-1
Step 4: Exit
In the above algorithm, LA is the linear array with N elements and K is the integer such that
K≤N. In this it deletes the Kth element from the linear array[LA].

Linear Search and Binary Search in Arrays


1. Introduction
Searching is the process of finding the location (index) of a particular element (called the key) in
a data structure like an array. Two common search techniques are:
• Linear Search
• Binary Search

2. Linear Search

Definition:
Linear Search is a simple search algorithm that checks every element of the array sequentially
until the desired element is found or the array ends.
Algorithm:
1. Start from index 0.
2. Compare each element with the key.
3. If a match is found, return the index.
4. If not found after the last element, return -1.
Time Complexity:

Case Time Complexity


Best Case O(1)
Average Case O(n)
Worst Case O(n)

3. Binary Search
Definition:
Binary Search is an efficient algorithm used to find an element in a sorted array by repeatedly
dividing the search interval in half.
• The algorithm requires two conditions –
1. The list must be sorted
2. One must have access to the middle element in any sublist.
• This means that one must essentially use a sorted array to hold the data
• But keeping data in a sorted array is very expensive when there are many insertions and
deletions (array limitation).
• In such situation, one may use a different data structure such as a linked list or a binary
search tree, to store the data.
Time Complexity:

Case Time Complexity


Best Case O(1)
Average Case O(log n)
Worst Case O(log n)

Note: The array must be sorted before performing binary search.

4. Comparison Between Linear and Binary Search

Criteria Linear Search Binary Search


Array Order Unsorted or Sorted Must be Sorted
Time Complexity O(n) O(log n)
Ease of Implementation Very Simple Slightly Complex
Use Case Small or unsorted data Large and sorted data

5. Applications
• Linear Search: Useful when data is unsorted or very small.
• Binary Search: Ideal for large, sorted data like dictionaries, databases, or index tables.

Lecture: Matrix Operations Using Arrays


Objective:
To understand how basic matrix operations (Addition, Subtraction, Multiplication, Transpose)
are performed using arrays in the C programming language.

Merge Two Sorted Arrays


Objective:
Merge two sorted arrays into a single sorted array.

Input:
• Array A of size m (sorted)
• Array B of size n (sorted)

Output:
• Array C of size m + n containing all elements from A and B, sorted

Idea:
• Use two pointers (or indices) to traverse both arrays.
• Compare the elements and insert the smaller one into the result array.
• If one array is exhausted, copy the remaining elements of the other.
Step-by-Step Algorithm:
1. Initialize pointers:
i = 0 // Pointer for array A
j = 0 // Pointer for array B
k = 0 // Pointer for result array C

2. Repeat while (i < m) and (j < n):


If A[i] <= B[j]:
C[k] = A[i]
i=i+1
Else:
C[k] = B[j]
j=j+1
k=k+1

3. Copy remaining elements of A (if any):


While i < m:
C[k] = A[i]
i=i+1
k=k+1

4. Copy remaining elements of B (if any):


While j < n:
C[k] = B[j]
j=j+1
k=k+1

5. Return or output array C

Time Complexity:
• O(m + n): Each element from both arrays is processed once.

Example:
Input:
A = [1, 3, 5]
B = [2, 4, 6]
Output:
C = [1, 2, 3, 4, 5, 6]
1. Matrix Representation in C
• A matrix is stored as a 2D array.
• Syntax: dataType matrix[row][column];
• For example, a 3x3 matrix is represented as int matrix[3][3];
• Each element is accessed using two indices: matrix[i][j] (i = row, j = column)

2. Matrix Addition
Conditions:
• Both matrices must have the same dimensions (i.e., same number of rows and columns).
Operation:
• Add corresponding elements from both matrices:
o result[i][j] = A[i][j] + B[i][j]

3. Matrix Subtraction
Conditions:
• Like addition, both matrices must have identical dimensions.
Operation:
• Subtract elements of matrix B from A:
o result[i][j] = A[i][j] - B[i][j]

4. Matrix Multiplication

Conditions:
• If matrix A is of size m × n and matrix B is of size n × p, then:
o The result matrix will be of size m × p.
Operation:
• Multiply each row of A with each column of B:
o result[i][j] = A[i][0] × B[0][j] + A[i][1] × B[1][j] + ... + A[i][n-1] × B[n-1][j]
• It involves dot product of row and column vectors.

5. Transpose of a Matrix
Objective:
• To flip a matrix over its diagonal.
• Rows become columns, and columns become rows.
Operation:
• transpose[j][i] = matrix[i][j]
• Useful in mathematical applications and optimization.

Pointer Arrays in Data Structures

1. Introduction to Pointers and Arrays


• A pointer is a variable that stores the memory address of another variable.
• An array is a collection of elements of the same type, stored in contiguous memory.
Pointer and array relationship:
• The name of an array is a pointer to its first element.
• Example:
• int arr[5] = {10, 20, 30, 40, 50};
• int *p = arr; // equivalent to int *p = &arr[0];
2. Pointer to Array
• You can use a pointer to traverse an array:
• for (int i = 0; i < 5; i++) {
• printf("%d ", *(p + i));
• }

3. Array of Pointers
Definition:
• An array of pointers is an array where each element is a pointer.
• Used to point to individual elements (or arrays) in memory.
Syntax:
int *arr[3]; // array of 3 integer pointers
Example Use Case:
int a = 10, b = 20, c = 30;
int *arr[3] = { &a, &b, &c };
• arr[0] points to a, arr[1] to b, etc.
Accessing Values:
printf("%d", *arr[1]); // prints 20

4. Pointer to an Array

Definition:
• A pointer that points to an entire array, not just an element.
Syntax:
int (*ptr)[5]; // pointer to array of 5 integers
Use:
int arr[5] = {1, 2, 3, 4, 5};
ptr = &arr;
printf("%d", (*ptr)[2]); // prints 3

5. Pointers and 2D Arrays


• A 2D array like int mat[3][3] is stored as a block of memory.
• You can use pointers to traverse or manipulate it:
int (*p)[3] = mat; // pointer to array of 3 ints
printf("%d", p[1][2]); // access second row, third column

6. Applications in Data Structures


• Used in:
o Dynamic memory allocation (e.g., creating arrays at runtime)
o Linked lists, trees, graphs
o Function arguments for passing large data efficiently
7. Advantages
• Efficient memory usage
• Easier dynamic data structure manipulation
• Enables passing large arrays to functions without copying

8. Caution
• Improper use can lead to:
o Memory leaks
o Dangling pointers
o Segmentation faults

Summary Table

Type Description Example Syntax

Pointer to element Points to one value int *p = &a;

Array of pointers Multiple pointers in one array int *arr[3];

Pointer to array One pointer to a whole array int (*p)[5];

Pointer to 2D array Points to rows in a 2D array int (*p)[3] = mat;

Dynamic Memory Allocation in C

1. What is Dynamic Memory Allocation?


Dynamic memory allocation allows a program to request memory during runtime rather than
at compile time.

Why Use Dynamic Allocation?


• Flexible memory use: Don’t waste memory with fixed-size arrays.
• Unknown input size: Allocate as needed.
• Essential for: Linked lists, trees, graphs, and other dynamic data structures.

2. Key Functions (in stdlib.h)

Function Purpose
malloc() Allocates uninitialized memory
calloc() Allocates zero-initialized memory
realloc() Changes size of allocated memory
free() Releases previously allocated memory

3. malloc() – Memory Allocation


• Allocates memory block of given size in bytes.
• Returns a void* (generic pointer), must be type-cast.
Syntax:
ptr = (int *)malloc(n * sizeof(int));
Example:
int *arr;
arr = (int *)malloc(5 * sizeof(int)); // allocates memory for 5 integers

4. calloc() – Clear Allocation


• Similar to malloc() but initializes all bits to 0.
Syntax:
ptr = (int *)calloc(n, sizeof(int));

5. realloc() – Resize Memory


• Changes the size of memory block previously allocated by malloc or calloc.
Syntax:
ptr = (int *)realloc(ptr, new_size * sizeof(int));

6. free() – Release Memory


• Frees memory and avoids memory leaks.
Syntax:
free(ptr);

7. Common Mistakes
• Not checking NULL after malloc() or calloc()
• Accessing memory after free()
• Memory leaks: Not calling free() leads to wasted memory
• Double free: Freeing the same memory twice

Use in Data Structures


Dynamic memory is critical for:
• Linked lists (malloc for nodes)
• Trees and graphs (dynamic node/edge creation)
• Stack/Queue with flexible size

Summary Table

Function Initializes? Can Resize? Needs Free?

malloc() (with realloc)

calloc() (zeros)
Function Initializes? Can Resize? Needs Free?

realloc() -

free() - - -

You might also like