0% found this document useful (0 votes)
1 views

Data Structures & Algorithms in C

The document provides an overview of data structures and algorithms in C, explaining the importance of organizing data effectively to optimize space and time complexities. It classifies data structures into linear and non-linear types, detailing popular structures such as arrays, linked lists, stacks, queues, binary trees, and graphs. Additionally, it covers basic operations and mathematical operations on arrays, including insertion, deletion, and arithmetic operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Data Structures & Algorithms in C

The document provides an overview of data structures and algorithms in C, explaining the importance of organizing data effectively to optimize space and time complexities. It classifies data structures into linear and non-linear types, detailing popular structures such as arrays, linked lists, stacks, queues, binary trees, and graphs. Additionally, it covers basic operations and mathematical operations on arrays, including insertion, deletion, and arithmetic operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Data Structures & Algorithms In C

Debapriya Mukherjee
What is Data Structure?

A data structure is a particular way of organising data in a computer so that it can be used effectively. The idea is
to reduce the space and time complexities of different tasks.

The choice of a good data structure makes it possible to perform a variety of critical operations effectively. An
efficient data structure also uses minimum memory space and execution time to process the structure. A data
structure is not only used for organising the data. It is also used for processing, retrieving, and storing data. There
are different basic and advanced types of data structures that are used in almost every program or software system
that has been developed. So we must have good knowledge of data structures.

Need Of Data Structure:


The structure of the data and the synthesis of the algorithm are relative to each other. Data presentation must be
easy to understand so the developer, as well as the user, can make an efficient implementation of the operation.
Data structures provide an easy way of organising, retrieving, managing, and storing data.

Here is a list of the needs for data.


Data structure modification is easy.
It requires less time.
Save storage memory space.
Data representation is easy.
Easy access to the large database
Classification/Types of Data Structures:
Linear Data Structure
Non-Linear Data Structure.

Linear Data Structure:


Elements are arranged in one dimension ,also
known as linear dimension.
Example: lists, stack, queue, etc.

Non-Linear Data Structure


Elements are arranged in one-many, many-one and
many-many dimensions.
Example: tree, graph, table, etc.
Most Popular Data Structures
1. Array:
An array is a collection of data items stored at contiguous memory locations. The idea is to
store multiple items of the same type together. This makes it easier to calculate the position of
each element by simply adding an offset to a base value, i.e., the memory location of the first
element of the array (generally denoted by the name of the array).
2. Linked Lists:
Like arrays, Linked List is a linear data structure. Unlike
arrays, linked list elements are not stored at a contiguous
location; the elements are linked using pointers.
3. Stack:
Stack is a linear data structure which follows a particular order in
which the operations are performed. The order may be LIFO(Last In
First Out) or FILO(First In Last Out). In stack, all insertion and
deletion are permitted at only one end of the list.

Stack Operations:
push(): When this operation is performed, an
element is inserted into the stack.
pop(): When this operation is performed, an
element is removed from the top of the stack and
is returned.
top(): This operation will return the last inserted
element that is at the top without removing it.
size(): This operation will return the size of the
stack i.e. the total number of elements present in
the stack.
isEmpty(): This operation indicates whether the
stack is empty or not.
4. Queue:
Like Stack, Queue is a linear structure which follows a particular order in which
the operations are performed. The order is First In First Out (FIFO). In the queue,
items are inserted at one end and deleted from the other end. A good example of
the queue is any queue of consumers for a resource where the consumer that
came first is served first. The difference between stacks and queues is in
removing. In a stack we remove the item the most recently added; in a queue, we
remove the item the least recently added.

Queue Operations:
Enqueue(): Adds (or stores) an element to the end of
the queue..
Dequeue(): Removal of elements from the queue.
Peek() or front(): Acquires the data element available
at the front node of the queue without deleting it.
rear(): This operation returns the element at the rear
end without removing it.
isFull(): Validates if the queue is full.
isNull(): Checks if the queue is empty.
5. Binary Tree:
Unlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are hierarchical data
structures. A binary tree is a tree data structure in which each node has at most two children, which are
referred to as the left child and the right child. It is implemented mainly using Links.
A Binary Tree is represented by a pointer to the topmost node in the tree. If the tree is empty, then the
value of root is NULL.

A Binary Tree node contains the following parts.


1. Data
2. Pointer to left child
3. Pointer to the right child
6. Binary Search Tree:
A Binary Search Tree is a Binary Tree following the additional properties:
The left part of the root node contains keys less than the root node key.
The right part of the root node contains keys greater than the root node key.
There is no duplicate key present in the binary tree.
A Binary tree having the following properties is known as Binary search tree (BST).
7. Matrix:
A matrix represents a collection of numbers arranged
in an order of rows and columns. It is necessary to
enclose the elements of a matrix in parentheses or
brackets.
A matrix with 9 elements is shown below.
8. Graph:

Graph is a data structure that consists of a collection of


nodes (vertices) connected by edges. Graphs are used to
represent relationships between objects and are widely
used in computer science, mathematics, and other fields.
Graphs can be used to model a wide variety of real-world
systems, such as social networks, transportation networks,
and computer networks.
Arrays
topics Covered:
Array Operations of insert in middle , starting and
End.
Array Mathematical operations.
Array operations
void insertAtEnd(int arr[], int *size, int value) { int main() { Key Points:
if (*size >= MAX_SIZE) { int arr[MAX_SIZE];
int size = 0;
No pointers are used, and array
printf("Array is full. Cannot insert.\n");
#include <stdio.h> return; operations are done with indices.
} // Initial array setup Functions modify the array size using a
#define MAX_SIZE 100 // Maximum size of the insertAtEnd(arr, &size, 10);
arr[*size] = value; pointer to size to reflect the updated
insertAtEnd(arr, &size, 20);
array (*size)++;
insertAtEnd(arr, &size, 30); size after operations.
}
printf("Initial Array: "); The array size (MAX_SIZE) is fixed, and
void display(int arr[], int size) {
display(arr, size);
for (int i = 0; i < size; i++) { void deleteFromBeginning(int arr[], int *size) { bounds are checked to prevent
printf("%d ", arr[i]); if (*size <= 0) { // Insertions overflow or underflow.
} printf("Array is empty. Cannot delete.\n"); insertAtBeginning(arr, &size, 5);
The display function shows the
printf("\n"); return; printf("After inserting 5 at the beginning: ");
} } display(arr, size); current state of the array after every
for (int i = 0; i < *size - 1; i++) { operation.
void insertAtBeginning(int arr[], int *size, int value) arr[i] = arr[i + 1]; insertAtMiddle(arr, &size, 15);
{ } printf("After inserting 15 at the middle: ");
if (*size >= MAX_SIZE) { (*size)--; display(arr, size);
printf("Array is full. Cannot insert.\n"); }
insertAtEnd(arr, &size, 40);
return;
printf("After inserting 40 at the end: ");
} void deleteFromMiddle(int arr[], int *size) {
display(arr, size); Output:
for (int i = *size; i > 0; i--) { if (*size <= 0) {
arr[i] = arr[i - 1]; printf("Array is empty. Cannot delete.\n"); // Deletions
} return; Initial Array: 10 20 30
deleteFromBeginning(arr, &size);
arr[0] = value; } printf("After deleting from the beginning: "); After inserting 5 at the beginning: 5 10 20 30
(*size)++; int mid = *size / 2; display(arr, size); After inserting 15 at the middle: 5 10 15 20 30
} for (int i = mid; i < *size - 1; i++) { After inserting 40 at the end: 5 10 15 20 30 40
arr[i] = arr[i + 1]; deleteFromMiddle(arr, &size); After deleting from the beginning: 10 15 20 30 40
void insertAtMiddle(int arr[], int *size, int value) { } printf("After deleting from the middle: ");
After deleting from the middle: 10 15 20 40
if (*size >= MAX_SIZE) { (*size)--; display(arr, size);
After deleting from the end: 10 15 20
printf("Array is full. Cannot insert.\n"); }
deleteFromEnd(arr, &size);
return;
printf("After deleting from the end: ");
} void deleteFromEnd(int arr[], int *size) {
display(arr, size);
int mid = *size / 2; if (*size <= 0) {
for (int i = *size; i > mid; i--) { printf("Array is empty. Cannot delete.\n");
return 0;
arr[i] = arr[i - 1]; return; }
} }
arr[mid] = value; (*size)--;
(*size)++; }
}
Array math operations
int main() {
int arr1[MAX_SIZE], arr2[MAX_SIZE], result[MAX_SIZE];
float resultDiv[MAX_SIZE];
Output
int size;

// Input array size


Enter the size of the arrays (max 100): 3
// Function to divide two arrays
void divideArrays(int arr1[], int arr2[], float printf("Enter the size of the arrays (max %d): ", MAX_SIZE); Enter elements of the first array:
scanf("%d", &size);
#include <stdio.h> result[], int size) { 234
#define MAX_SIZE 100 // Maximum size of the array for (int i = 0; i < size; i++) { if (size > MAX_SIZE || size <= 0) {
if (arr2[i] != 0) { printf("Invalid size.\n"); Enter elements of the second array:
void display(int arr[], int size) { result[i] = (float)arr1[i] / arr2[i];
}
return 1;
123
for (int i = 0; i < size; i++) { } else {
printf("%d ", arr[i]); printf("Error: Division by zero at index // Input elements for the first array
} %d\n", i); printf("Enter elements of the first array:\n");
printf("\n"); result[i] = 0; // Assign a default value for (int i = 0; i < size; i++) { Addition of arrays:
} }
}
scanf("%d", &arr1[i]);
357
}
// Function to add two arrays } Subtraction of arrays:
// Input elements for the second array
void addArrays(int arr1[], int arr2[], int result[], int size) { printf("Enter elements of the second array:\n"); 111
for (int i = 0; i < size; i++) { // Function to calculate the sum of array for (int i = 0; i < size; i++) {
result[i] = arr1[i] + arr2[i]; elements scanf("%d", &arr2[i]); Multiplication of arrays:
} int sumOfElements(int arr[], int size) { }
2 6 12
} int sum = 0;
for (int i = 0; i < size; i++) {
// Perform mathematical operations Division of arrays:
printf("\nAddition of arrays:\n");
// Function to subtract two arrays sum += arr[i]; addArrays(arr1, arr2, result, size); 2.00 1.50 1.33
} display(result, size);
void subtractArrays(int arr1[], int arr2[], int result[], int size) Sum of elements in the first array: 9
{ return sum;
for (int i = 0; i < size; i++) { }
printf("\nSubtraction of arrays:\n");
subtractArrays(arr1, arr2, result, size);
Average of elements in the first array: 3.00
result[i] = arr1[i] - arr2[i]; display(result, size); Square of elements in the first array:
} // Function to calculate the average of array
} elements printf("\nMultiplication of arrays:\n"); 4 9 16
multiplyArrays(arr1, arr2, result, size);
float averageOfElements(int arr[], int size) {
display(result, size);
// Function to multiply two arrays int sum = sumOfElements(arr, size);
void multiplyArrays(int arr1[], int arr2[], int result[], int size) return (float)sum / size; printf("\nDivision of arrays:\n");
{ } divideArrays(arr1, arr2, resultDiv, size);
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
printf("%.2f ", resultDiv[i]);
result[i] = arr1[i] * arr2[i]; // Function to calculate the square of each
}
} element in the array printf("\n");
} void squareOfElements(int arr[], int result[], int
size) { // Additional operations
for (int i = 0; i < size; i++) { printf("\nSum of elements in the first array: %d\n", sumOfElements(arr1, size));
printf("Average of elements in the first array: %.2f\n", averageOfElements(arr1, size));
result[i] = arr[i] * arr[i];
} printf("\nSquare of elements in the first array:\n");
} squareOfElements(arr1, result, size);
display(result, size);

return 0;
}

You might also like