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

Algorithm To Perform Push

Push operator

Uploaded by

Ronit Deb
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Algorithm To Perform Push

Push operator

Uploaded by

Ronit Deb
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Algorithm to perform push, pop and peek operation on stack

Algorithm

Push Operation

1. Check if the stack is full (top == MAX_SIZE - 1).


a. If full, print "Stack Overflow" and exit the function.
2. If not full:
a. Increment the top index.
b. Add the new value to stack[top].

Pop Operation

1. Check if the stack is empty (top == -1).


a. If empty, print "Stack Underflow" and return.
2. If not empty:
a. Retrieve the value at stack[top].
b. Decrement the top index.

Peek Operation

1. Check if the stack is empty (top == -1).


a. If empty, print "Stack is Empty" and return.
2. If not empty:
a. Return the value at stack[top].

Algorithm to check nesting of parantheses using stack

Algorithm

1. Initialize an empty stack to store opening parentheses.


2. Traverse the input string:
a. If the current character is an opening parenthesis ((, {, [), push it onto the
stack.
b. If the current character is a closing parenthesis (), }, ]):
i. Check if the stack is empty:
1. If the stack is empty, the parentheses are unbalanced. Return
False.
ii. Otherwise, pop the top element from the stack and check if it
matches the type of the closing parenthesis:
1. If it doesn’t match, return False.
3. After traversing the string:
a. If the stack is empty, the parentheses are balanced. Return True.
b. Otherwise, return False.

Algorithm to Reverse a List

Algorithm

1. Initialize two pointers:


a. start at the first element (index 0).
b. end at the last element (index n-1, where n is the size of the array).
2. Swap elements at start and end indices.
3. Increment the start pointer and decrement the end pointer.
4. Repeat step 2 and step 3 until start is greater than or equal to end.
5. The array is now reversed.

Algorithm to evaluate a postfix expression

Algorithm

1. Initialize an empty stack for storing operands.


2. Traverse the postfix expression from left to right:
a. If the current character is an operand:
i. Convert it to a number (if needed) and push it onto the stack.
b. If the current character is an operator (+, -, *, /):
i. Pop the top two elements from the stack.
ii. Apply the operator to the two popped elements (second popped is the
left operand, first popped is the right operand).
iii. Push the result back onto the stack.
3. After processing the entire expression:
a. The result of the expression is the top element in the stack. Pop it and return
as the final result.
Algorithm to Convert Infix to Prefix Expression

Algorithm Steps

1. Reverse the Infix Expression: Start by reversing the given infix expression. While
reversing, make sure to swap the parentheses:
a. Replace ( with ) and vice versa.
2. Convert the Reversed Expression to Postfix: Apply the usual infix to postfix
conversion using a stack:
a. If the character is an operand, add it directly to the result.
b. If the character is an operator, pop operators from the stack until an operator
with lower precedence or a parenthesis is at the top of the stack, and then
push the current operator onto the stack.
c. If the character is a parenthesis, handle it similarly to the standard infix-to-
postfix conversion.
3. Reverse the Postfix Expression: After converting the reversed infix to postfix,
reverse the resulting postfix expression to get the prefix expression.

Algorithm create a linked list and perform insertions and deletions of all cases. Write
functions to sort and finally delete the entire list at once.

• Node Structure: We define a Node structure that contains an integer data and a
pointer to the next node (next).
• Insertion Functions:
• insertAtBeginning: Adds a node at the start.
• insertAtEnd: Adds a node at the end by traversing to the last node.
• insertAfter: Adds a node after a specified node (by data).
• Deletion Functions:
• deleteFromBeginning: Deletes the first node.
• deleteFromEnd: Deletes the last node by traversing to the second-last node.
• deleteNode: Deletes a node with a specific value.
• Sorting Function:
• sortList: Implements bubble sort to sort the linked list in ascending order.
• Delete Entire List:
• deleteList: Deletes all nodes in the list by traversing through and freeing each
node.
• Printing the List:
• printList: Traverses and prints all the elements in the list.
Algorithm to implement a linear queue

Algorithm Steps

1. Define the Queue Structure:


a. Create a structure Queue with an array arr to store the elements of the
queue.
b. Keep track of the front index (index of the front element in the queue) and
rear index (index of the last element in the queue).
c. Initialize front and rear to -1 (indicating the queue is empty).
d. Define a MAX_SIZE for the queue (maximum number of elements it can
hold).
2. Enqueue Operation:
a. If the queue is full (rear == MAX_SIZE - 1), print "Queue Overflow" and
exit.
b. If the queue is empty (front == -1), set front to 0.
c. Increment rear and insert the new element at the rear index.
3. Dequeue Operation:
a. If the queue is empty (front == -1), print "Queue Underflow" and exit.
b. Remove the element at the front index and increment front.
c. If the front surpasses rear, reset front and rear to -1 (indicating the
queue is empty).
4. Peek Operation:
a. If the queue is empty, return -1.
b. Return the element at the front index.
5. Check if Queue is Empty:
a. Return 1 if the queue is empty, otherwise return 0.
Algorithm to search an element in an array using binary search

Binary Search Algorithm Steps:

1. Initialize:
a. Define two pointers, low and high, representing the bounds of the search
range.
b. Initially, low is the first index (0), and high is the last index (n-1, where n is
the size of the array).
2. Iterate:
a. Calculate the middle index mid = low + (high - low) / 2 to avoid
overflow.
b. Compare the middle element (arr[mid]) with the target element (key):
i. If arr[mid] == key, then the element is found and return the mid
index.
ii. If arr[mid] < key, then the target must be in the right half, so set
low = mid + 1.
iii. If arr[mid] > key, then the target must be in the left half, so set
high = mid - 1.
3. Termination:
a. The search continues until low <= high. If low becomes greater than high,
then the element is not present in the array, and return -1.

Algorithm to search an array using linear search

Function linearSearch:

Takes an array arr[], its size n, and the key (element to search for).
It loops through the array from the first element to the last.
If the element at the current index matches key, it returns the index.
If the loop completes without finding the key, it returns -1, indicating the element is
not present.
Main Function:

Defines an array arr[] and the element key to search.


Calls linearSearch to find the index of the key.
Prints the result: either the index where the element was found or a message
indicating the element was not found.

Insertion Sort Algorithm

Function insertionSort:

Takes an array arr[] and its size n.


It starts from the second element (index 1) and compares it with the previous
elements.
If the current element (key) is smaller than an element at index j, that element is
shifted one position to the right to make room for the key.
This process continues until the correct position for the key is found, and it is
inserted at that position.

Function printArray:

This function is used to print the array after sorting.

Main Function:

Defines an unsorted array arr[] and its size n.


Calls insertionSort to sort the array.
Prints the array before and after sorting.

Selection Sort Algorithm Steps:

Function selectionSort:

Takes an array arr[] and its size n.


It iterates through the array with index i to represent the current boundary of the
sorted part.
It then finds the minimum element in the unsorted part (from index i+1 to n-1), and
swaps it with the element at index i.
This process continues until the array is fully sorted.

Function printArray:

This function is used to print the array before and after sorting.

Main Function:

Defines an unsorted array arr[] and calculates the size n.


Calls selectionSort to sort the array.
Prints the array before and after sorting.

Breadth-First Search (BFS) Algorithm

Graph Representation:

We represent the graph using an adjacency list. Each vertex points to a list of its
adjacent vertices.
A Node structure is used to represent each vertex and its adjacent vertices in the
adjacency list.
createGraph:
Allocates memory for the graph structure and initializes each adjacency list to
NULL.
addEdge:
Adds an edge to the graph by creating a new node and inserting it into the adjacency
list of both the source and destination vertices (since it's an undirected graph).

BFS:

Initializes a visited array to keep track of visited vertices.


A queue is used to perform the BFS traversal.
The algorithm starts from a given vertex, marks it as visited, and enqueues it. It then
continues to dequeue vertices and visit all their unvisited neighbors, enqueuing
them until all reachable vertices are processed.

Main Function:

A graph with 4 vertices is created, and edges are added. The BFS traversal starts
from vertex 0 and explores all reachable vertices.

Depth-First Search (DFS) Algorithm

Graph Representation:

The graph is represented using an adjacency list. Each vertex points to a list of its
adjacent vertices.
A Node structure represents each vertex and its adjacent vertices in the adjacency
list.

createGraph:

Allocates memory for the graph structure and initializes each adjacency list to
NULL.

addEdge:

Adds an edge to the graph by creating a new node and inserting it into the adjacency
list of both the source and destination vertices (since the graph is undirected).

DFS (Recursive):

Takes a graph, vertex, and visited[] array as arguments.


Marks the current vertex as visited and prints it.
Recursively visits all its unvisited neighbors by calling DFS for each unvisited
adjacent vertex.

Main Function:

Creates a graph with 4 vertices and adds edges.


Initializes the visited[] array to keep track of which nodes have been visited.
Calls the recursive DFS starting from vertex 0

You might also like