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

Data Structure

The document provides an overview of data types in programming, distinguishing between primitive and composite data types, including their characteristics and examples. It also covers time and space complexity, explaining how to analyze algorithms and their efficiency. Additionally, it discusses stack and queue data structures, their operations, and applications in programming.

Uploaded by

nimendragiri
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)
3 views

Data Structure

The document provides an overview of data types in programming, distinguishing between primitive and composite data types, including their characteristics and examples. It also covers time and space complexity, explaining how to analyze algorithms and their efficiency. Additionally, it discusses stack and queue data structures, their operations, and applications in programming.

Uploaded by

nimendragiri
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/ 14

1.

Primitive Data Types:


Primitive data types are the basic building blocks of data manipulation. These types store
single values and have predefined sizes. They are fundamental for performing operations like
arithmetic and logical computations.

Characteristics of Primitive Data Types:

 Directly operated by machine instructions.


 Require a fixed amount of memory.
 Cannot be further divided into smaller data types.
 Support arithmetic and logical operations.

Types of Primitive Data Types:

1. Integer (int, short, long, byte)


o Stores whole numbers (positive or negative).
o Example:

java
CopyEdit
int num = 100;

o Memory Usage (Java Example):


 byte (1 byte), short (2 bytes), int (4 bytes), long (8 bytes).
2. Floating-Point (float, double)
o Stores decimal numbers.
o Example:

java
CopyEdit
float price = 10.99f;
double pi = 3.14159;

oMemory Usage:
 float (4 bytes), double (8 bytes).
3. Character (char)
o Stores a single character.
o Example:

java
CopyEdit
char letter = 'A';

oMemory Usage: 2 bytes (Java) due to Unicode support.


4. Boolean (true/false)
o Stores only true or false.
o Example:

java
CopyEdit
boolean isPassed = true;

o Memory Usage: 1 byte (depends on the language).

2. Composite Data Types:


Composite data types are made up of multiple primitive data types. They allow the storage
and manipulation of multiple values in a structured way.

Characteristics of Composite Data Types:

 Can store multiple values of different or same types.


 Used for complex data representation.
 Some allow dynamic memory allocation.

Types of Composite Data Types:

1. Arrays
o A collection of elements of the same type stored in contiguous memory.
o Elements are accessed using an index.
o Example:

java
CopyEdit
int numbers[] = {1, 2, 3, 4, 5};

o Memory Usage: Depends on element type and size.


2. Structures (struct in C, class in Java/Python)
o A user-defined data type that groups related variables of different types.
o Example (C Structure):

c
CopyEdit
struct Student {
char name[50];
int age;
float marks;
};

o Example (Java Class):

java
CopyEdit
class Student {
String name;
int age;
float marks;
}

o Memory Usage: Sum of all member sizes + padding for alignment.


Union
A union is a user-defined data type similar to a structure, but with a key difference: all
members share the same memory location, meaning only one member can hold a value at
any given time.

Characteristics of Union:

 Uses shared memory, meaning it can store different types but only one at a time.
 Helps in memory-efficient programs.
 Occupies memory equal to the largest member in it.
 Used in cases where a variable can take multiple types but only one is active at a time.

3. Classes (Object-Oriented Composite Type)


o A blueprint for creating objects, combining data and methods.
o Example:

java
CopyEdit
class Book {
String title;
int pages;
}

o Memory Usage: Depends on attributes and object references.


4. Linked Lists
o A collection of nodes where each node stores data and a reference to the next
node.
o Example (Node in Java):

java
CopyEdit
class Node {
int data;
Node next;
}

o Memory Usage: Extra space needed for pointers.


5. Stacks and Queues
o Stack: Follows LIFO (Last In, First Out).
o Queue: Follows FIFO (First In, First Out).
o Example (Stack in Java):

java
CopyEdit
Stack<Integer> stack = new Stack<>();
stack.push(10);

o Memory Usage: Depends on elements stored.


6. Trees and Graphs
o Tree: Hierarchical data structure (e.g., Binary Tree).
o Graph: Consists of nodes (vertices) and edges (connections).
o Example (Tree Node in Java):

java
CopyEdit
class TreeNode {
int data;
TreeNode left, right;
}

o Memory Usage: Depends on nodes and pointers.

Comparison: Primitive vs Composite Data Types

Feature Primitive Data Type Composite Data Type


Definition Stores a single value Stores multiple values or objects
Complexity Simple More complex
Memory Usage Fixed Can be dynamic
Operations Arithmetic, logical Requires traversal, manipulation
Example int, char, boolean Array, Linked List, Tree

1. Time Complexity

Time complexity is a measure of the amount of time an algorithm takes to complete its
execution as a function of the size of the input. It reflects the number of basic operations or
steps an algorithm performs.

Formal Definition:
Time complexity is the computational complexity that describes the relationship between the
input size (denoted as n) and the number of steps required to execute the algorithm.

How to Analyze Time Complexity

1. Count the Basic Operations: Analyze loops, recursion, and other control structures.
2. Focus on Input Size (n): Time complexity is expressed as a function of n.
3. Identify Growth Rate: Use asymptotic notations to describe the rate of growth of the
algorithm's execution time.

Common Asymptotic Notations for Time Complexity:

 O(1) – Constant Time: The algorithm executes in the same amount of time, regardless of
input size.
o Example: Accessing an element in an array.
 O(log n) – Logarithmic Time: The algorithm's execution time grows logarithmically with the
input size.
o Example: Binary search.
 O(n) – Linear Time: The execution time grows proportionally to the input size.
o Example: Traversing an array.
 O(n²) – Quadratic Time: The execution time grows quadratically with the input size.
o Example: Nested loops in algorithms like bubble sort.
 O(2ⁿ) – Exponential Time: Execution time doubles with each increment in input size.
o Example: Recursive solutions like solving the Tower of

2. Space Complexity

Space complexity is a measure of the amount of memory an algorithm uses during its
execution. It considers both the input size and any additional memory required for temporary
or auxiliary variables.

Formal Definition:
Space complexity is the computational complexity that describes the relationship between the
input size (denoted as n) and the memory required by the algorithm.

Components of Space Complexity:

1. Fixed Part: Memory required for constants and variables that do not depend on the input
size.
2. Variable Part: Memory required for dynamically allocated structures, recursion stacks, or
other temporary data structures.

Common Asymptotic Notations for Space Complexity:

 O(1) – Constant Space: The algorithm uses a fixed amount of memory, regardless of input
size.
o Example: Swapping two variables.
 O(n) – Linear Space: The memory usage grows linearly with input size.
o Example: Storing an array of size n.
 O(n²) – Quadratic Space: Memory usage grows quadratically with input size.
o Example: 2D arrays or matrices.

Importance of Time and Space Complexity

1. Efficiency Evaluation: Helps determine if an algorithm can handle large inputs


effectively.
2. Optimization: Guides developers in selecting or designing algorithms with better
performance.
3. Resource Management: Ensures minimal use of computational resources.
4. Comparison: Allows comparing different algorithms for the same problem.

Stack
A stack is a linear data structure that follows the LIFO (Last In, First Out) principle. In a
stack, the last element added is the first one to be removed. It is often compared to a stack of
plates where you can only add or remove plates from the top.

Key Features of a Stack:

1. Linear Data Structure: Elements are arranged in a linear order.


2. LIFO Principle: The last element added is the first one to be removed.
3. Operations Restricted to One End: All insertions and deletions occur at the top of the stack.

Representation of a Stack:

 Can be implemented using an array or a linked list.


 A special pointer, called the top, keeps track of the last inserted element in the stack.

Applications of Stack:

1. Function Call Management: Used in recursion to store function calls.


2. Expression Evaluation: Used in infix-to-postfix conversion and evaluation of postfix
expressions.
3. Undo Operations: Used in text editors and IDEs for undo/redo functionality.
4. Backtracking: Used in solving maze problems or puzzles like Sudoku.
5. DFS

6. parenthesis matching: Stacks are used to check if an expression has balanced


parentheses.

o Example: The expression {[()]} is valid, but {[(])} is not.


o Steps: Push opening brackets onto the stack and pop when encountering a
matching closing bracket.

7. Browser Navigation (Back and Forward Operations)

Primitive Operations on Stack:

1. Push Operation (Insertion):


Adds an element to the top of the stack.

o Steps:
1. Check if the stack is full (in the case of a fixed-size stack).
2. If not full, increment the top pointer.
3. Add the new element at the top position.
o Time Complexity: O(1)
2. Pop Operation (Deletion):
Removes the top element from the stack.

 Steps:
1. Check if the stack is empty.
2. If not empty, remove the element at the top and decrement the top pointer.
 Time Complexity: O(1)

3. Peek/Top Operation:
Retrieves the value of the top element without removing it.

 Steps:
1. Check if the stack is empty.
2. If not empty, return the value at the top.
 Time Complexity: O(1)

4. IsEmpty Operation:
Checks whether the stack is empty.

 Steps:
1. If top == -1, return true (stack is empty).
2. Otherwise, return false.
 Time Complexity: O(1)

5. IsFull Operation:
Checks whether the stack is full (only applicable to fixed-size stacks).

 Steps:
1. If top == maxSize - 1, return true (stack is full).
2. Otherwise, return false.
 Time Complexity: O(1)

Example Stack Operations in a Sequence:

Consider a stack with a maximum size of 5, starting empty (top = -1).

1. Push(10): Stack = [10], Top = 0


2. Push(20): Stack = [10, 20], Top = 1
3. Peek(): Returns 20
4. Pop(): Removes 20, Stack = [10], Top = 0
5. IsEmpty(): Returns false

a. Infix Expression

 Definition: In an infix expression, the operator is placed between operands.


o Example: A + B * C.
 Problem with Infix:
Infix expressions require operator precedence and parentheses to indicate order, making
them difficult to evaluate directly using computers.
 Application of Stack:
o Conversion to Postfix or Prefix: Stacks are used to rearrange infix expressions into
postfix or prefix for easier computation.
o Example: Converting A + B * C to Postfix: A B C * +.
 Evaluation: Direct evaluation of infix expressions is rarely done using stacks but involves the
use of operator precedence rules.

b. Postfix Expression (Reverse Polish Notation)

 Definition: In a postfix expression, the operator comes after the operands.


o Example: A B + C *.
 Advantages:
o No need for parentheses.
o Operator precedence is implicitly handled.
 Evaluation Using Stack:
o Scan the expression from left to right.
o Push operands onto the stack.
o When an operator is encountered, pop the required number of operands, perform
the operation, and push the result back.
o Example:
For the expression 2 3 + 4 *:
 Push 2, Push 3.
 Encounter +: Pop 2 and 3, calculate 5, Push 5.
 Push 4.
 Encounter *: Pop 5 and 4, calculate 20. Result: 20.

c. Prefix Expression (Polish Notation)

 Definition: In a prefix expression, the operator comes before the operands.


o Example: * + A B C.
 Advantages:
o Like postfix, no need for parentheses.
 Evaluation Using Stack:
o Scan the expression from right to left.
o Push operands onto the stack.
o When an operator is encountered, pop the required operands, perform the
operation, and push the result back.
o Example:
For the expression * + 2 3 4:
 Push 4, Push 3, Push 2.
 Encounter +: Pop 2 and 3, calculate 5, Push 5.
 Encounter *: Pop 5 and 4, calculate 20. Result: 20.

2. Recursion

 Definition: Recursion is a programming technique where a function calls itself to solve


smaller instances of a problem.
 Role of Stack:
o Recursion is implemented using a system stack, called the call stack.
o For every recursive call:
 The function's parameters, local variables, and return address are pushed
onto the stack.
 When the base condition is met, the stack unwinds, and each stored value is
popped and used.

Example of Recursion Using a Stack: Factorial Calculation


cpp
CopyEdit
int factorial(int n) {
if (n == 0) return 1; // Base condition
return n * factorial(n - 1); // Recursive call
}

How the Stack Works:


For factorial(4):

1. factorial(4) calls factorial(3) → Push parameters and local variables for


factorial(4).
2. factorial(3) calls factorial(2) → Push factorial(3) state.
3. factorial(2) calls factorial(1) → Push factorial(2) state.
4. Base case (factorial(0)) returns 1.
5. The stack unwinds, multiplying results stored in the stack to return 4! = 24.

Applications of Recursion Using Stacks:

 Backtracking: Solving problems like mazes, N-Queens, and Sudoku.


 Tree Traversals: Preorder, Inorder, and Postorder traversals of binary trees.
 Graph Traversals: Depth-First Search (DFS).

Queues and Primitive Operations on Queue

Definition of Queue

A queue is a linear data structure that follows the FIFO (First In, First Out) principle. In a
queue, the first element added is the first one to be removed, much like a queue of people
waiting in line.

Features of Queue

1. FIFO Principle: The element that enters the queue first is removed first.
2. Two Ends:
o Front: Points to the element to be removed next.
o Rear: Points to the position where a new element will be added.
3. Applications:
o Process scheduling in operating systems.
o Managing requests in printers.
o Data buffering in communication systems.

Representation of Queue

Queues can be implemented using:

 Arrays (fixed size, simple implementation).


 Linked Lists (dynamic size).

Primitive Operations on Queue

1. Enqueue Operation (Insertion)

 Purpose: Add an element to the rear of the queue.


 Steps:
1. Check if the queue is full (in a fixed-size implementation).
2. If not full, increment the rear pointer.
3. Add the new element at the rear position.
 Time Complexity: O(1).
 Example:
Adding 10 and 20 to a queue:

cpp
CopyEdit
void enqueue(int queue[], int &rear, int maxSize, int value) {
if (rear == maxSize - 1) {
cout << "Queue Overflow!";
return;
}
queue[++rear] = value;
}

2. Dequeue Operation (Deletion)

 Purpose: Remove an element from the front of the queue.


 Steps:
1. Check if the queue is empty.
2. If not empty, remove the element at the front position.
3. Increment the front pointer.
 Time Complexity: O(1).
 Example:
Removing an element from the queue:
cpp
CopyEdit
int dequeue(int queue[], int &front, int &rear) {
if (front > rear) {
cout << "Queue Underflow!";
return -1; // Return error code
}
return queue[front++];
}

3. Peek/Front Operation

 Purpose: View the front element without removing it.


 Steps:
1. Check if the queue is empty.
2. If not empty, return the element at the front pointer.
 Time Complexity: O(1).
 Example:

cpp
CopyEdit
int peek(int queue[], int front, int rear) {
if (front > rear) {
cout << "Queue is Empty!";
return -1; // Return error code
}
return queue[front];
}

4. IsEmpty Operation

 Purpose: Check if the queue is empty.


 Steps:
1. If front > rear, return true.
2. Otherwise, return false.
 Time Complexity: O(1).

5. IsFull Operation

 Purpose: Check if the queue is full (in fixed-size implementation).


 Steps:
1. If rear == maxSize - 1, return true.
2. Otherwise, return false.
 Time Complexity: O(1).

Example of Queue Operations


Scenario: Fixed-size queue with a capacity of 5.

1. Initial State: Queue is empty (front = 0, rear = -1).


2. Enqueue(10): Queue = [10], front = 0, rear = 0.
3. Enqueue(20): Queue = [10, 20], front = 0, rear = 1.
4. Peek(): Returns 10 (front element).
5. Dequeue(): Removes 10, Queue = [20], front = 1, rear = 1.
6. IsEmpty(): Returns false.
7. Dequeue(): Removes 20, Queue = [], front = 2, rear = 1.
8. IsEmpty(): Returns true.

Applications of Queue

1. CPU Scheduling: Tasks are managed in a queue for execution.


2. Printer Queue: Manages print jobs in the order they are received.
3. Breadth-First Search (BFS): Used in graph traversal algorithms.
4. Data Buffers: Queues are used in IO buffers and packet switching.

What is a Circular Queue?


A circular queue is similar to a linear queue as it is also based on the FIFO (First In First
Out) principle except that the last position is connected to the first position in a circular
queue that forms a circle. It is also known as a Ring Buffer.

Operations on Circular Queue


The following are the operations that can be performed on a circular queue:

o Front: It is used to get the front element from the Queue.


o Rear: It is used to get the rear element from the Queue.
o enQueue(value): This function is used to insert the new value in the Queue. The
new element is always inserted from the rear end.
o deQueue(): This function deletes an element from the Queue. The deletion in a
Queue always takes place from the front end.

Applications of Circular Queue


The circular Queue can be used in the following scenarios:

o Memory management: The circular queue provides memory management. As we


have already seen that in linear queue, the memory is not managed very efficiently.
But in case of a circular queue, the memory is managed efficiently by placing the
elements in a location which is unused.
o CPU Scheduling: The operating system also uses the circular queue to insert the
processes and then execute them.
o Traffic system: In a computer-control traffic system, traffic light is one of the best
examples of the circular queue. Each light of traffic light gets ON one by one after
every jinterval of time. Like red light gets ON for one minute then yellow light for one
minute and then green light. After green light, the red light gets ON.

Enqueue operation
The steps of enqueue operation are given below:

o First, we will check whether the Queue is full or not.


o Initially the front and rear are set to -1. When we insert the first element in a Queue,
front and rear both are set to 0.
o When we insert a new element, the rear gets incremented, i.e., rear=rear+1.

Scenarios for inserting an element


There are two scenarios in which queue is not full:

o If rear != max - 1, then rear will be incremented to mod(maxsize) and the new value
will be inserted at the rear end of the queue.
o If front != 0 and rear = max - 1, it means that queue is not full, then set the value of
rear to 0 and insert the new element there.
There are two cases in which the element cannot be inserted:

o When front ==0 && rear = max-1, which means that front is at the first position of
the Queue and rear is at the last position of the Queue.
o front== rear + 1;
Algorithm to insert an element in a circular queue

Step1: IF(REAR+1)%MAX=FRONT
Write " OVERFLOW "
Goto step 4
[End OF IF]

Step 2: IF FRONT = -1 and REAR = -1


SET FRONT = REAR = 0
ELSE IF REAR = MAX - 1 and FRONT ! = 0
SET REAR = 0
ELSE
SET REAR = (REAR + 1) % MAX
[END OF IF]

Step 3: SET QUEUE[REAR] = VAL

Step 4: EXIT

Dequeue Operation
The steps of dequeue operation are given below:
o First, we check whether the Queue is empty or not. If the queue is empty, we cannot
perform the dequeue operation.
o When the element is deleted, the value of front gets decremented by 1.
o If there is only one element left which is to be deleted, then the front and rear are
reset to -1.
Algorithm to delete an element from the circular queue

Step 1: IF FRONT = -1
Write " UNDERFLOW "
Goto Step 4
[END of IF]

Step 2: SET VAL = QUEUE[FRONT]

Step 3: IF FRONT = REAR


SET FRONT = REAR = -1
ELSE
IF FRONT = MAX -1
SET FRONT = 0
ELSE
SET FRONT = FRONT + 1
[END of IF]
[END OF IF]

Step 4: EXIT

You might also like