0% found this document useful (0 votes)
15 views13 pages

1111 M Ss LM

The document discusses different data structures including arrays, linked lists, stacks, queues, trees, graphs, hash tables, and heaps. It provides details on the characteristics, storage structure, operations, and use cases of these common data structures.

Uploaded by

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

1111 M Ss LM

The document discusses different data structures including arrays, linked lists, stacks, queues, trees, graphs, hash tables, and heaps. It provides details on the characteristics, storage structure, operations, and use cases of these common data structures.

Uploaded by

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

DATA STRUCTURES AND APPLICATION

CAP4103

School of Engineering
Department of Computer Science and Engineering

Submitted By
Student Name Rakesh Dey sarkar
Enrolment Number 230160307023
Programme Masters in Computer Application
Department Computer Science and Engineering
Session/Semester 2023-2025/Second Semester
Submitted To
Faculty Name Ms. Sapna Sharma
Q1.What is Data Structure ? Explain Various Types of Data Structure
.
Ans: A data structure is a way of organizing and storing data to perform operations
efficiently. It defines a set of rules or conventions for organizing and managing data,
which allows for easier access, modification, and processing. Data structures are
essential components in computer science and are used in various applications to
solve different types of problems.

There are two main types of data structures:

1. Primitive Data Structures:


 These are the basic or fundamental data structures.
 Examples include integers, floating-point numbers, characters, and
booleans.
2. Composite Data Structures:
 These structures are built by combining primitive data types and
organizing them in a specific way.
 Examples include arrays, linked lists, stacks, queues, trees, and graphs.

Common operations performed on data structures include:

 Insertion: Adding new data.


 Deletion: Removing existing data.
 Traversal: Visiting and processing all elements.
 Searching: Finding the location of a specific element.
 Sorting: Arranging elements in a specific order.

The choice of a data structure depends on the requirements of the specific


application and the operations that need to be performed efficiently. Each data
structure has its own advantages and disadvantages, and selecting the right one is
crucial for optimizing the performance of algorithms and overall system efficiency.
Data structures are fundamental components in computer science that enable
efficient organization, storage, and manipulation of data. There are various types of
data structures, each with its own characteristics, use cases, and advantages. Here, I'll
explain some of the most common types:

1. Arrays:
 An array is a collection of elements, each identified by an index or a
key.
 Elements in an array are stored in contiguous memory locations.
 Accessing elements in an array is fast, O(1) time complexity.
 Insertion and deletion operations can be slow, especially in the middle,
as shifting may be required.
2. Linked Lists:
 A linked list is a linear data structure where elements are stored in
nodes, and each node points to the next node in the sequence.
 Dynamic in nature, which means it can grow or shrink during program
execution.
 Insertion and deletion are generally faster compared to arrays,
especially in the middle.
 Random access to elements is slower, O(n) time complexity.
3. Stacks:
 A stack is a last-in, first-out (LIFO) data structure.
 Elements can only be added or removed from the top of the stack.
 Common operations include push (to add an element) and pop (to
remove the top element).
 Used for managing function calls, undo mechanisms, and parsing
expressions.
4. Queues:
 A queue is a first-in, first-out (FIFO) data structure.
 Elements are added at the rear (enqueue) and removed from the front
(dequeue).
 Common operations include enqueue and dequeue.
 Used in scenarios like job scheduling, breadth-first search algorithms.
5. Trees:
 A hierarchical data structure with a root node and subtrees of child
nodes.
 Binary Trees have at most two children per node.
 Binary Search Trees (BST) maintain an ordering property that allows for
efficient search, insertion, and deletion.
 Common tree-based algorithms include binary search, AVL trees, and
heaps.
6. Graphs:
 A collection of nodes (vertices) and edges connecting these nodes.
 Directed graphs have edges with a direction, while undirected graphs
do not.
 Used to represent relationships between entities and solve problems
like shortest path algorithms and network flow.
7. Hash Tables:
 Utilizes a hash function to map keys to indices in an array.
 Provides fast insertion, deletion, and lookup operations on average,
with O(1) complexity.
 Collision resolution methods, like chaining or open addressing, handle
situations where multiple keys map to the same index.
8. Heaps:
 A specialized tree-based data structure that satisfies the heap property.
 Max Heap: Parent nodes are greater than or equal to their child nodes.
 Min Heap: Parent nodes are less than or equal to their child nodes.
 Used for priority queues and heap sort.

These data structures serve as building blocks for designing algorithms and solving
various computational problems. The choice of the appropriate data structure
depends on the specific requirements and characteristics of the problem at hand.
Q.2 What do you mean by Array? Describe storage structure of
array. Also explain various types of Arrays in Details.

Ans: An array is a fundamental data structure in computer science that stores a


collection of elements, each identified by an index or a key. The elements in an array
are stored in contiguous memory locations, meaning they are placed next to each
other in the computer's memory. This arrangement allows for efficient access to
individual elements by their index.

Key characteristics of arrays include:

1. Indexing: Elements in an array are accessed using an index or a key. The


index is typically an integer that starts from zero for the first element, one for
the second, and so on.
2. Contiguous Memory: Array elements are stored in adjacent memory
locations. This feature enables quick and direct access to any element based
on its index.
3. Fixed Size: In most programming languages, the size of an array is fixed at
the time of declaration. Once defined, the size usually cannot be changed
during runtime. Some languages, however, support dynamic arrays or
resizable arrays.

Here's a simple example in Python:

# Declaring an array

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

# Accessing elements

first_element = my_array[0] # Value: 1

second_element = my_array[1] # Value: 2

# Modifying elements

my_array[2] = 10 # Array becomes [1, 2, 10, 4, 5]


Arrays are widely used in programming for tasks like storing lists of items, iterating
Sets are a fundamental data structure in Python used for storing count += 1
collections of unique elements. Here are some key points about sets:
### Loop Control Statements:

1. Unordered Collection: Sets do not maintain any order Python provides several control statements that can alter the behavior of
among elements. loops:
2. Unique Elements: Sets only store unique elements. If you
try to add a duplicate element, it won't be added. - `break`: Terminates the loop immediately.
3. Mutable: You can modify a set after it has been created.
Elements can be added or removed. - `continue`: Skips the rest of the code inside the loop for the current
4. Immutable Elements: Elements in a set must be iteration and proceeds to the next iteration.
immutable (e.g., numbers, strings, tuples).
5. Set Operations: Sets support various operations such as - `pass`: Used when a statement is syntactically required but you want to
union, intersection, difference, and symmetric difference. do nothing.
6. Use Cases: Sets are often used for tasks like removing
Example with loop control statements:
duplicates from a list, checking membership, or
performing mathematical operations involving sets.
```python

for i in range(10):
A dictionary in Python is a data structure used to store collections of
key-value pairs. Here are some key points about dictionaries:
if i == 3:

continue # Skip printing 3


1. Key-Value Pairs: Each element in a dictionary consists of
a key and its associated value.
elif i == 6:
2. Unordered: Like sets, dictionaries do not maintain any
order among elements.
break # Exit the loop when reaching 6
3. Mutable: You can modify a dictionary after it has been
created. Keys can be added, removed, or updated. else:
4. Keys Must be Unique and Immutable: Keys in a
dictionary must be unique and immutable (e.g., numbers, print(
strings, tuples).
5. Values Can be Mutable or Immutable: Values ### Nested Loops:
associated with keys can be of any data type and can be
mutable or immutable. You can also have loops inside other loops, known as nested loops.
6. Fast Lookup: Dictionaries offer fast retrieval of values
based on keys. Example of a nested loop:
7. Use Cases: Dictionaries are commonly used for storing
mappings between objects, such as storing user ```python
information where each user ID is associated with user
details. for i in range(3):
a
for j in range(2):
Loops in programming are constructs that allow you to execute a block of
code repeatedly based on a condition. In Python, there are mainly two types print(i, j)
of loops: `for` loops and `while` loops.
In Python, arrays are often referred to as lists. Lists are a
fundamental data structure that allow you to store and manipulate
collections of items. Here's an overview of lists in Python:
### For Loops:

A `for` loop is used to iterate over a sequence (such as a list, tuple, string, or Lists:
range) or any iterable object. It executes a block of code for each element in
the sequence.
 Lists are ordered collections of elements, which means
Example:
the elements are stored in a specific sequence and can
be accessed by their index.
```python
 Lists can contain elements of different data types,
fruits = ["apple", "banana", "cherry"] such as integers, floats, strings, or even other lists.

for fruit in fruits:


 Lists are mutable, meaning you can modify them after
they have been created. You can add, remove, or
change elements in a list.
print(fruit)
 Lists are defined using square brackets [ ], and
### While Loops: elements are separated by commas.
Conditions, also known as conditional statements or control
A `while` loop repeatedly executes a block of code as long as a specified structures, allow you to control the flow of your program based on
condition is certain conditions. In Python, the most common conditional
statements are if, elif (short for "else if"), and else.
```python

while condition: If Statement:

# code block to be executed as long as the condition is true


The if statement is used to execute a block of code if a condition is
Example: true.

```python
If-Else Statement:
count = 0

The else statement is used in conjunction with if to execute a block


while count < 5:
of code if the condition in the if statement is false.
print(count) print("x is not greater than 10")

Elif Statement: Combining Logical Operators:

The elif statement allows you to check for multiple conditions. It stands You can combine multiple conditions using logical operators to
for "else if". You can have multiple elif statements followed by an create more complex conditions.
optional else statement.

x=5
String Methods:
y = 20

1. len(): Returns the length of the string.


if x > 0 and y < 15 or x == 5:
2.lower() and upper(): Convert the string to lowercase or uppercase,
respectively print("Complex condition is true")

3. strip(): Removes leading and trailing whitespace from the string.

4. split(): Splits the string into a list of substrings based on a delimiter Bitwise operators in Python are used to perform operations on
(default is whitespace). individual bits of integers. Here's an explanation of the bitwise
operators you mentioned:
5. join(): Joins the elements of an iterable (e.g., list) into a string using
the specified separator.
& (Bitwise AND):
6. replace(): Replaces occurrences of a substring with another substring.

The & operator performs a bitwise AND operation between


7. find() and index(): Search for a substring within the string and return
corresponding bits of two integers. It returns a 1 in each bit position
the index of the first occurrence. find() returns -1 if not found, while
where both bits are 1, otherwise, it returns 0.
index() raises a ValueError.

8. startswith() and endswith(): Check if the string starts or ends with a a=5 # Binary: 101
specified substring.
b=3 # Binary: 011
9. count(): Count the occurrences of a substring within the string.
result = a & b

print(result) # Output: 1 (Binary: 001)


Logical operators in Python are used to combine multiple conditional
statements or expressions. There are three main logical operators: and,
or, and not. | (Bitwise OR):

and Operator: The | operator performs a bitwise OR operation between


corresponding bits of two integers. It returns a 1 in each bit position
where at least one bit is 1, otherwise, it returns 0.
The and operator returns True if both operands are True, otherwise, it
returns False.
a=5 # Binary: 101

x=5 b=3 # Binary: 011

y = 10 result = a | b

if x > 0 and y < 15: print(result) # Output: 7 (Binary: 111)

print("Both conditions are true")

or Operator: ~ (Bitwise NOT):

The or operator returns True if at least one of the operands is True, The ~ operator performs a bitwise NOT operation on a single
otherwise, it returns False. integer. It returns the one's complement of the integer, which
means it flips all the bits of the integer, turning 0s into 1s and vice
versa.
x=5

y = 20 a=5 # Binary: 101

if x > 10 or y < 15: result = ~a

print("At least one condition is true") print(result) # Output: -6 (Binary:


11111111111111111111111111111010 in 2's complement)

not Operator:
For loop and while loop A for loop is used when you know how
many times you want to execute a block of code. It iterates over a
The not operator is a unary operator that returns the opposite of the sequence (such as a list, tuple, string, or range) and executes the
boolean value of its operand. It negates the condition. block of code for each item in the sequence.

x=5

if not x > 10:


While Loop:

A while loop is used when you want to execute a block of code


repeatedly as long as a specified condition is true. The loop continues
iterating until the condition becomes false.

Differences:

 Control over iteration: In a for loop, you have control


over the iteration through a predefined sequence. In a
while loop, you have control over the iteration based on a
condition.
 Condition: For loops are used when you know the
number of iterations in advance. While loops are used
when you're not sure how many iterations are needed,
but you know the condition under which the loop should
continue.
 Initialization and Update: In a for loop, the variable used
for iteration is typically initialized and updated
automatically. In a while loop, you need to initialize and
update the control variable manually within the loop.

In Python, the + operator can be used both as a unary operator and as


a binary operator, depending on its usage.

Unary + Operator:

As a unary operator, the + symbol is used to indicate a positive number.


It doesn't actually change the value of the operand; it's just used to
explicitly denote a positive number, as numbers are assumed to be
positive by default.

Binary + Operator:

As a binary operator, the + symbol is used for addition. It adds two


operands together.

Example:

 When used as a binary operator, the + symbol performs


addition.
 When used as a unary operator, the + symbol can be used
to explicitly denote a positive number, but it doesn't
change the value of the operand.

Unary - Operator:

As a unary operator, the - symbol is used to negate a number. It


changes the sign of the operand to its right.

Binary - Operator:

As a binary operator, the - symbol is used for subtraction. It subtracts


the right operand from the left operand.

 When used as a binary operator, the - symbol performs


subtraction.
 When used as a unary operator, the - symbol negates the
operand's value, changing its sign.

Arrays are widely used in programming for tasks like storing lists of items, iterating
through collections, and implementing algorithms that require constant-time access
to elements. Despite their efficiency for random access, arrays may have limitations,
such as fixed size and potential inefficiencies in insertions and deletions, particularly
in the middle of the array. In such cases, other data structures like linked lists may be
more suitable.

The storage structure of arrays is characterized by the arrangement of elements in


contiguous memory locations. This arrangement provides several advantages, such
as efficient random access and simplicity in memory addressing. Here are the key
aspects of the storage structure in arrays:

1. Contiguous Memory Allocation:


 Array elements are stored one after the other in memory, in contiguous
or consecutive locations. This means that the memory addresses of
array elements are sequential.
 The contiguous storage allows for direct and efficient access to any
element using its index. The memory address of the first element is
used as a reference point.
2. Indexing:
 Elements in an array are accessed using indices. The index indicates the
position of an element within the array.
 The formula for accessing the memory location of an element is often
based on the starting address of the array and the size of each element.
For example, if the array starts at address A and each element occupies
S bytes, the address of the element at index i is given by A + i * S.
3. Fixed-size Allocation:
 The size of an array is typically fixed at the time of declaration. Once
defined, the array size remains constant throughout its lifetime.
 Fixed-size allocation simplifies memory management and allows for
direct computation of memory addresses during compilation.
4. Memory Efficiency:
 Contiguous storage makes efficient use of memory, as there is no need
for additional space between elements. This is in contrast to some data
structures, like linked lists, which may require extra memory for
pointers.
 The absence of extra memory overhead results in better cache locality,
which can improve performance by reducing cache misses during data
access.

Here's a simple illustration of the storage structure of an array in memory:

| Element 0 | Element 1 | Element 2 | Element 3 | ... | Element n-1 |


|-----------|-----------|-----------|-----------|-----|-------------|
^ Starting address of the array
In this diagram, each box represents the memory location of an array element, and
the arrow indicates the starting address of the array. Accessing an element involves a
direct calculation based on the index and the size of each element. This simplicity
and efficiency in memory addressing make arrays a fundamental and widely used
data structure in programming.

In computer science, arrays come in various types, each serving specific purposes and
addressing different requirements. Here are some of the common types of arrays:

1.One-dimensional Array:
 A simple, linear array where elements are stored in a single line or row.
 Accessing elements involves using a single index.
 Examples include arrays of integers, characters, or floating-point
numbers.
# One-dimensional array in Python

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

2.Multi-dimensional Array:
 Arrays with more than one dimension. Common types include 2D arrays
(matrices) and 3D arrays.
 Elements are accessed using multiple indices corresponding to the array's
dimensions.
 Useful for representing tables, grids, and matrices.
# Two-dimensional array (matrix) in Python

matrix = [

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

3. Dynamic Array:
 An array that can dynamically resize during runtime.
 Provides a higher-level abstraction than traditional fixed-size arrays.
 Commonly used in languages like Python with lists or Java with ArrayList.
# Dynamic array in Python using a list

dynamic_array = [1, 2, 3]

dynamic_array.append(4) # Resize happens automatically


4. Jagged Array:
 An array of arrays where each sub-array can have a different size.
 Useful when the number of elements varies in different dimensions.
 Offers flexibility but may result in uneven memory allocation.
// Jagged array in C#

int[][] jaggedArray = new int[3][];

jaggedArray[0] = new int[] { 1, 2, 3 };

jaggedArray[1] = new int[] { 4, 5 };

jaggedArray[2] = new int[] { 6, 7, 8, 9 };

5. Sparse Array:
 An array in which most of the elements have the same default value, typically
zero or null.
 Efficiently stores and represents arrays with a small number of non-default
elements.
 Often used in applications dealing with large datasets with sparse
characteristics.
# Sparse array in Python using a dictionary

sparse_array = {0: 1, 2: 3, 5: 6}

6. String Array:
 An array where each element is a string.
 Useful for storing and manipulating a collection of strings.
// String array in Java

String[] stringArray = {"apple", "banana", "orange"};

7. Circular Array:
 An array where the last element is followed by the first element, creating a
circular structure.
 Useful in scenarios where cyclic operations are required, like rotating
elements.
# Circular array in Python

circular_array = [3, 4, 5, 1, 2] # Represents rotation

These types of arrays cater to different programming scenarios, providing flexibility,


efficiency, and abstraction based on the specific requirements of the application or
algorithm. Choosing the appropriate type of array depends on the problem at hand
and the desired characteristics of the data structure.

You might also like