0% found this document useful (0 votes)
6 views30 pages

Pseudo Code DSA

Pseudo code for DSA programs

Uploaded by

SSPriya SSPriya
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)
6 views30 pages

Pseudo Code DSA

Pseudo code for DSA programs

Uploaded by

SSPriya SSPriya
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/ 30

PSEUDO CODE FOR LINEAR SEARCH

LinearSearch(array, target)

1. for i = 0 to length(array) - 1

2. if array[i] == target

3. return i

4. return -1

PSEUDO CODE FOR BINARY SEARCH

BinarySearch(array, target)

1. left ← 0

2. right ← length(array) - 1

3. while left ≤ right

4. mid ← (left + right) // 2

5. if array[mid] == target

6. return mid

7. else if array[mid] < target

8. left ← mid + 1

9. else

10. right ← mid - 1

11. return -1

PSEUDO CODE FOR BUBBLE SORT

BubbleSort(array)

1. n ← length(array)

2. for i ← 0 to n - 1

3. for j ← 0 to n - i - 2

4. if array[j] > array[j + 1]

5. swap(array[j], array[j + 1])


6. return array

PSEUDO CODE FOR INSERTION SORT

InsertionSort(array)

1. n ← length(array)

2. for i ← 1 to n - 1

3. key ← array[i]

4. j←i-1

5. while j ≥ 0 and array[j] > key

6. array[j + 1] ← array[j]

7. j←j-1

8. array[j + 1] ← key

9. return array

PSEUDO CODE FOR SELECTION SORT

SelectionSort(array)

1. n ← length(array)

2. for i ← 0 to n - 1

3. minIndex ← i

4. for j ← i + 1 to n - 1

5. if array[j] < array[minIndex]

6. minIndex ← j

7. swap(array[i], array[minIndex])

8. return array

PSEUDO CODE FOR IMPLEMENTATION OF SINGLE LINKED LIST

1. Define Node:

- data

- next ← NULL
2. Initialize:

- head ← NULL

Operations:

3. CreateNode(data):

- newNode ← create Node(data)

- return newNode

4. InsertAtBeginning(data):

- newNode ← CreateNode(data)

- newNode.next ← head

- head ← newNode

5. InsertAtEnd(data):

- newNode ← CreateNode(data)

- if head is NULL:

- head ← newNode

- else:

- temp ← head

- while temp.next ≠ NULL:

- temp ← temp.next

- temp.next ← newNode

6. InsertInMiddle(data, pos):

- newNode ← CreateNode(data)

- if pos = 1:

- InsertAtBeginning(data)

- else:
- temp ← head

- for i ← 1 to pos - 2:

- if temp.next = NULL:

- break

- temp ← temp.next

- newNode.next ← temp.next

- temp.next ← newNode

7. DeleteAtBeginning():

- if head is NOT NULL:

- head ← head.next

8. DeleteAtEnd():

- if head is NOT NULL:

- if head.next is NULL:

- head ← NULL

- else:

- temp ← head

- while temp.next.next ≠ NULL:

- temp ← temp.next

- temp.next ← NULL

9. DeleteAtMiddle(pos):

- if head is NOT NULL:

- if pos = 1:

- DeleteAtBeginning()

- else:

- temp ← head
- for i ← 1 to pos - 2:

- if temp.next = NULL:

- break

- temp ← temp.next

- if temp.next ≠ NULL:

- temp.next ← temp.next.next

10. Display():

- temp ← head

- while temp ≠ NULL:

- print temp.data

- temp ← temp.next

PSEUDO CODE FOR IMPLEMENTATION OF DOUBLE LINKED LIST


1. Define Node:
- data
- next ← NULL
- prev ← NULL

2. Initialize:
- head ← NULL

Operations:

3. CreateNode(data):
- newNode ← create Node(data)
- return newNode

4. InsertAtBeginning(data):
- newNode ← CreateNode(data)
- if head is NULL:
- head ← newNode
- else:
- newNode.next ← head
- head.prev ← newNode
- head ← newNode

5. InsertAtEnd(data):
- newNode ← CreateNode(data)
- if head is NULL:
- head ← newNode
- else:
- temp ← head
- while temp.next ≠ NULL:
- temp ← temp.next
- temp.next ← newNode
- newNode.prev ← temp

6. InsertInMiddle(data, pos):
- newNode ← CreateNode(data)
- if pos = 1:
- InsertAtBeginning(data)
- else:
- temp ← head
- for i ← 1 to pos - 2:
- if temp.next = NULL:
- break
- temp ← temp.next
- if temp.next ≠ NULL:
- newNode.next ← temp.next
- temp.next.prev ← newNode
- temp.next ← newNode
- newNode.prev ← temp

7. DeleteAtBeginning():
- if head ≠ NULL:
- if head.next = NULL:
- head ← NULL
- else:
- head ← head.next
- head.prev ← NULL

8. DeleteAtEnd():
- if head ≠ NULL:
- if head.next = NULL:
- head ← NULL
- else:
- temp ← head
- while temp.next ≠ NULL:
- temp ← temp.next
- temp.prev.next ← NULL

9. DeleteAtMiddle(pos):
- if head ≠ NULL:
- if pos = 1:
- DeleteAtBeginning()
- else:
- temp ← head
- for i ← 1 to pos - 2:
- if temp.next = NULL:
- break
- temp ← temp.next
- if temp.next ≠ NULL:
- temp.next ← temp.next.next
- if temp.next ≠ NULL:
- temp.next.prev ← temp

10. DisplayForward():
- temp ← head
- while temp ≠ NULL:
- print temp.data
- temp ← temp.next

11. DisplayBackward():
- temp ← head
- while temp.next ≠ NULL:
- temp ← temp.next
- while temp ≠ NULL:
- print temp.data
- temp ← temp.prev

PSEUDO CODE FOR IMPLEMENTATION OF CIRCULAR LINKED LIST

1. Define Node:

- data

- next ← NULL
2. Initialize:

- head ← NULL

Operations:

3. CreateNode(data):

- newNode ← create Node(data)

- return newNode

4. InsertAtBeginning(data):

- newNode ← CreateNode(data)

- if head is NULL:

- head ← newNode

- newNode.next ← head

- else:

- temp ← head

- while temp.next ≠ head:

- temp ← temp.next

- newNode.next ← head

- temp.next ← newNode

- head ← newNode

5. InsertAtEnd(data):

- newNode ← CreateNode(data)

- if head is NULL:

- head ← newNode

- newNode.next ← head
- else:

- temp ← head

- while temp.next ≠ head:

- temp ← temp.next

- temp.next ← newNode

- newNode.next ← head

6. InsertInMiddle(data, pos):

- newNode ← CreateNode(data)

- if pos = 1:

- InsertAtBeginning(data)

- else:

- temp ← head

- for i ← 1 to pos - 2:

- if temp.next = head:

- break

- temp ← temp.next

- newNode.next ← temp.next

- temp.next ← newNode

7. DeleteAtBeginning():

- if head ≠ NULL:

- if head.next = head:

- head ← NULL

- else:

- temp ← head

- while temp.next ≠ head:

- temp ← temp.next
- temp.next ← head.next

- head ← head.next

8. DeleteAtEnd():

- if head ≠ NULL:

- if head.next = head:

- head ← NULL

- else:

- temp ← head

- while temp.next.next ≠ head:

- temp ← temp.next

- temp.next ← head

9. DeleteAtMiddle(pos):

- if head ≠ NULL:

- if pos = 1:

- DeleteAtBeginning()

- else:

- temp ← head

- for i ← 1 to pos - 2:

- if temp.next = head:

- break

- temp ← temp.next

- if temp.next ≠ head:

- temp.next ← temp.next.next

10. Display():

- if head ≠ NULL:
- temp ← head

- do:

- print temp.data

- temp ← temp.next

- while temp ≠ head

PSEUDO CODE FOR POLYNOMIAL ADDITION USING LINKED LIST


1. Define Node:
- coefficient
- exponent
- next ← NULL

2. Initialize:
- head1 ← NULL // for first polynomial
- head2 ← NULL // for second polynomial
- result ← NULL // for resulting polynomial

Operations:

3. CreateNode(coefficient, exponent):
- newNode ← create Node(coefficient, exponent)
- return newNode

4. InsertAtEnd(head, coefficient, exponent):


- newNode ← CreateNode(coefficient, exponent)
- if head is NULL:
- head ← newNode
- else:
- temp ← head
- while temp.next ≠ NULL:
- temp ← temp.next
- temp.next ← newNode
- return head

5. PolynomialAddition(head1, head2):
- result ← NULL
- while head1 ≠ NULL and head2 ≠ NULL:
- if head1.exponent > head2.exponent:
- result ← InsertAtEnd(result, head1.coefficient, head1.exponent)
- head1 ← head1.next
- else if head1.exponent < head2.exponent:
- result ← InsertAtEnd(result, head2.coefficient, head2.exponent)
- head2 ← head2.next
- else:
- sum ← head1.coefficient + head2.coefficient
- if sum ≠ 0:
- result ← InsertAtEnd(result, sum, head1.exponent)
- head1 ← head1.next
- head2 ← head2.next

- while head1 ≠ NULL:


- result ← InsertAtEnd(result, head1.coefficient, head1.exponent)
- head1 ← head1.next

- while head2 ≠ NULL:


- result ← InsertAtEnd(result, head2.coefficient, head2.exponent)
- head2 ← head2.next

- return result

6. DisplayPolynomial(head):
- temp ← head
- while temp ≠ NULL:
- if temp.coefficient > 0 and temp ≠ head:
- print "+" temp.coefficient "x^" temp.exponent
- else:
- print temp.coefficient "x^" temp.exponent
- temp ← temp.next

PSEUDO CODE FOR IMPLEMENTATION OF STACK


1. Define Node:
- data
- next ← NULL

2. Initialize:
- top ← NULL
- maxSize ← predefined limit (if using a fixed-size stack)
- currentSize ← 0
Operations:

3. CreateNode(data):
- newNode ← create Node(data)
- return newNode

4. Push(data):
- if isFull():
- return "Stack Overflow"
- newNode ← CreateNode(data)
- newNode.next ← top
- top ← newNode
- currentSize ← currentSize + 1

5. Pop():
- if isEmpty():
- return "Stack Underflow"
- temp ← top
- top ← top.next
- currentSize ← currentSize - 1
- return temp.data

6. Peek():
- if isEmpty():
- return "Stack is empty"
- return top.data

7. IsEmpty():
- if top = NULL:
- return true
- else:
- return false

8. IsFull():
- if currentSize == maxSize:
- return true
- else:
- return false

9. Display():
- if isEmpty():
- return "Stack is empty"
- temp ← top
- while temp ≠ NULL:
- print temp.data
- temp ← temp.next

PSEUDO CODE FOR IMPLEMENTATION OF STACK USING LINKED LIST


1. Define Node:

- data

- next ← NULL

2. Initialize:

- top ← NULL

- maxSize ← predefined limit (optional, if using a fixed-size stack)

- currentSize ← 0

Operations:

3. CreateNode(data):

- newNode ← create Node(data)

- return newNode

4. Push(data):

- if isFull():

- return "Stack Overflow"

- newNode ← CreateNode(data)

- newNode.next ← top

- top ← newNode

- currentSize ← currentSize + 1

5. Pop():
- if isEmpty():

- return "Stack Underflow"

- temp ← top

- top ← top.next

- currentSize ← currentSize - 1

- return temp.data

6. Peek():

- if isEmpty():

- return "Stack is empty"

- return top.data

7. IsEmpty():

- if top = NULL:

- return true

- else:

- return false

8. IsFull():

- if currentSize == maxSize:

- return true

- else:

- return false

9. Display():

- if isEmpty():

- return "Stack is empty"

- temp ← top
- while temp ≠ NULL:

- print temp.data

- temp ← temp.next

PSEUDO CODE FOR CONVERSION OF EXPRESSION

1. Precedence(operator):

if operator is '+' or '-': return 1

if operator is '*' or '/': return 2

if operator is '^': return 3

return 0

2. InfixToPostfix(expression):

stack ← empty

result ← empty

for each char in expression:

if char is operand: result ← result + char

else if char is '(': stack ← stack + char

else if char is ')':

while stack not empty and top(stack) ≠ '(':

result ← result + pop(stack)

pop(stack) // discard '('

else if char is operator:

while stack not empty and precedence(top(stack)) ≥ precedence(char):

result ← result + pop(stack)

stack ← stack + char

while stack not empty:

result ← result + pop(stack)

return result
InfixToPrefix(expression):

reverse(expression)

replace '(' with ')', ')' with '('

postfix ← InfixToPostfix(expression)

reverse(postfix)

return postfix

Main():

infix ← "A + B * (C - D)"

postfix ← InfixToPostfix(infix)

print "Postfix:", postfix

prefix ← InfixToPrefix(infix)

print "Prefix:", prefix

PSEUDO CODE FOR EVALUATION OF EXPRESSION

1. Precedence(op):

if op = '+' or '-': return 1

if op = '*' or '/': return 2

if op = '^': return 3

return 0

2. ApplyOperation(a, b, op):

if op = '+': return a + b

if op = '-': return a - b

if op = '*': return a * b

if op = '/': return a / b

if op = '^': return a ^ b
3. EvaluateInfix(expression):

values ← empty stack // To store numbers

operators ← empty stack // To store operators

for each char in expression:

if char is whitespace: continue

if char is number:

push(values, char)

else if char = '(':

push(operators, char)

else if char = ')':

while top(operators) ≠ '(':

b ← pop(values)

a ← pop(values)

op ← pop(operators)

push(values, ApplyOperation(a, b, op))

pop(operators) // Remove '('

else if char is operator:

while operators not empty and Precedence(top(operators)) ≥ Precedence(char):

b ← pop(values)

a ← pop(values)

op ← pop(operators)

push(values, ApplyOperation(a, b, op))

push(operators, char)

while operators not empty:

b ← pop(values)

a ← pop(values)

op ← pop(operators)

push(values, ApplyOperation(a, b, op))


return pop(values)

PSEUDO CODE FOR IMPLEMENTATION OF QUEUE

Queue:

Initialize:

front ← 0

rear ← -1

size ← 0

maxSize ← predefined limit (size of the queue)

queue ← array of size maxSize

Operations:

1. Enqueue(data):

if isFull():

return "Queue Overflow"

rear ← (rear + 1) % maxSize

queue[rear] ← data

size ← size + 1

2. Dequeue():

if isEmpty():

return "Queue Underflow"

data ← queue[front]

front ← (front + 1) % maxSize

size ← size - 1

return data
3. Peek():

if isEmpty():

return "Queue is empty"

return queue[front]

4. IsEmpty():

if size == 0:

return true

return false

5. IsFull():

if size == maxSize:

return true

return false

6. Display():

if isEmpty():

return "Queue is empty"

temp ← front

while temp ≠ rear:

print queue[temp]

temp ← (temp + 1) % maxSize

print queue[rear] // Print the last element

PSEUDO CODE FOR IMPLEMENTATION OF INPUT RESTRICTED QUEUE

InputRestrictedQueue:

Initialize:

front ← 0
rear ← -1

size ← 0

maxSize ← predefined limit (size of the queue)

queue ← array of size maxSize

Operations:

1. Enqueue(data):

if isFull():

return "Queue Overflow"

rear ← (rear + 1) % maxSize

queue[rear] ← data

size ← size + 1

2. DequeueFromFront():

if isEmpty():

return "Queue Underflow"

data ← queue[front]

front ← (front + 1) % maxSize

size ← size - 1

return data

3. DequeueFromRear():

if isEmpty():

return "Queue Underflow"

data ← queue[rear]

rear ← (rear - 1 + maxSize) % maxSize

size ← size - 1
return data

4. PeekFront():

if isEmpty():

return "Queue is empty"

return queue[front]

5. PeekRear():

if isEmpty():

return "Queue is empty"

return queue[rear]

6. IsEmpty():

if size == 0:

return true

return false

7. IsFull():

if size == maxSize:

return true

return false

8. Display():

if isEmpty():

return "Queue is empty"

temp ← front

while temp ≠ rear:

print queue[temp]
temp ← (temp + 1) % maxSize

print queue[rear] // Print the last element

PSEUDO CODE FOR BINARY TREE TRAVERSAL

Node:

data

left ← NULL

right ← NULL

1. PreorderTraversal(node):

if node ≠ NULL:

print node.data

PreorderTraversal(node.left)

PreorderTraversal(node.right)

2. InorderTraversal(node):

if node ≠ NULL:

InorderTraversal(node.left)

print node.data

InorderTraversal(node.right)

3. PostorderTraversal(node):

if node ≠ NULL:

PostorderTraversal(node.left)

PostorderTraversal(node.right)

print node.data

PSEUDO CODE FOR QUICK SORT

1. QuickSort(arr, low, high):


if low < high:

pivotIndex ← Partition(arr, low, high)

QuickSort(arr, low, pivotIndex - 1)

QuickSort(arr, pivotIndex + 1, high)

2. Partition(arr, low, high):

pivot ← arr[high]

i ← low - 1

for j ← low to high - 1:

if arr[j] ≤ pivot:

i←i+1

swap(arr[i], arr[j])

swap(arr[i + 1], arr[high])

return i + 1

PSEUDO CODE FOR MERGE SORT

1. MergeSort(arr, left, right):

if left < right:

mid ← (left + right) / 2

MergeSort(arr, left, mid)

MergeSort(arr, mid + 1, right)

Merge(arr, left, mid, right)

2. Merge(arr, left, mid, right):

n1 ← mid - left + 1

n2 ← right - mid

create leftArr[1...n1], rightArr[1...n2]


for i ← 0 to n1 - 1:

leftArr[i] ← arr[left + i]

for j ← 0 to n2 - 1:

rightArr[j] ← arr[mid + 1 + j]

i ← 0, j ← 0, k ← left

while i < n1 and j < n2:

if leftArr[i] ≤ rightArr[j]:

arr[k] ← leftArr[i]

i←i+1

else:

arr[k] ← rightArr[j]

j←j+1

k←k+1

while i < n1:

arr[k] ← leftArr[i]

i←i+1

k←k+1

while j < n2:

arr[k] ← rightArr[j]

j←j+1

k←k+1

PSEUDO CODE FOR KNAP SACK

GreedyKnapSack(weight[], value[], capacity, n):

Create array profitPerWeight[n]

for i ← 0 to n - 1:

profitPerWeight[i] ← value[i] / weight[i]

Sort items by profitPerWeight in descending order


totalProfit ← 0

remainingCapacity ← capacity

for i ← 0 to n - 1:

if weight[i] ≤ remainingCapacity:

totalProfit ← totalProfit + value[i]

remainingCapacity ← remainingCapacity - weight[i]

else:

fraction ← remainingCapacity / weight[i]

totalProfit ← totalProfit + (value[i] * fraction)

break

return totalProfit

PSEUDO CODE FOR MINIMUM SPANNING TREE USING PRIM'S ALGORITHM

1. PrimMST(graph, V):

Initialize MSTSet[V] ← false // Track visited vertices

Initialize key[V] ← ∞ // Minimum edge weights

Initialize parent[V] ← -1 // Track MST structure

key[0] ← 0 // Start from the first vertex

for count ← 0 to V - 1:

u ← ExtractMin(key, MSTSet) // Find the minimum key vertex not in MSTSet

MSTSet[u] ← true // Include u in MST

for each v in graph[u]:

if graph[u][v] ≠ 0 and MSTSet[v] = false and graph[u][v] < key[v]:

parent[v] ← u

key[v] ← graph[u][v]

PrintMST(parent, graph)

2. ExtractMin(key, MSTSet):

minKey ← ∞
minIndex ← -1

for v ← 0 to V - 1:

if MSTSet[v] = false and key[v] < minKey:

minKey ← key[v]

minIndex ← v

return minIndex

3. PrintMST(parent, graph):

print "Edge Weight"

for i ← 1 to V - 1:

print parent[i] " - " i " " graph[i][parent[i]]

PSEUDO CODE FOR MINIMUM SPANNING TREE USING KRUSKAL

1. KruskalMST(graph, V, E):

Initialize result ← [] // Store MST edges

Initialize parent[V] ← -1 // For union-find

Initialize rank[V] ← 0 // For union-find

Sort all edges by weight in ascending order

for each edge (u, v, weight) in sorted edges:

uRoot ← Find(u, parent)

vRoot ← Find(v, parent)

if uRoot ≠ vRoot:

result.append((u, v, weight))

Union(uRoot, vRoot, parent, rank)

PrintMST(result)

2. Find(node, parent):

if parent[node] = -1:

return node
return Find(parent[node], parent)

3. Union(uRoot, vRoot, parent, rank):

if rank[uRoot] > rank[vRoot]:

parent[vRoot] ← uRoot

elif rank[uRoot] < rank[vRoot]:

parent[uRoot] ← vRoot

else:

parent[vRoot] ← uRoot

rank[uRoot] ← rank[uRoot] + 1

4. PrintMST(result):

print "Edge Weight"

for (u, v, weight) in result:

print u " - " v " " weight

PSEUDO CODE FOR DIJKSTRA ALGORITHM

1. Dijkstra(graph, V, source):

dist[V] ← ∞ // Initialize distances to ∞

dist[source] ← 0 // Distance to source is 0

visited[V] ← false // Track visited nodes

for count ← 0 to V - 1:

u ← ExtractMin(dist, visited) // Get the vertex with min distance

visited[u] ← true // Mark u as visited

for each neighbor v of u:

if graph[u][v] ≠ 0 and visited[v] = false and dist[u] + graph[u][v] < dist[v]:

dist[v] ← dist[u] + graph[u][v]

PrintShortestPaths(source, dist)
2. ExtractMin(dist, visited):

minDist ← ∞

minIndex ← -1

for v ← 0 to V - 1:

if visited[v] = false and dist[v] < minDist:

minDist ← dist[v]

minIndex ← v

return minIndex

3. PrintShortestPaths(source, dist):

print "Vertex Distance from Source"

for i ← 0 to V - 1:

print i " " dist[i]

PSEUDOCODE FOR MULTI-STAGE GRAPH (FORWARD APPROACH)

1. MultiStageGraph(graph, n):
Create cost[n] ← ∞ // Cost from source to each vertex
Create path[n] ← -1 // To track the shortest path
cost[1] ← 0 // Start from source (node 1)
for i ← 1 to n - 1:
for each neighbor j of i:
if cost[i] + graph[i][j] < cost[j]:
cost[j] ← cost[i] + graph[i][j]
path[j] ← i
PrintShortestPath(path, n, cost[n])

2. PrintShortestPath(path, n, minCost):
Create stack ← []
node ← n
while node ≠ -1:
stack.push(node)
node ← path[node]
print "Shortest Path: "
while stack is not empty:
print stack.pop()
print "Minimum Cost: " minCost

PSEUDOCODE FOR MULTI-STAGE GRAPH (BACKWARD APPROACH)

1. MultiStageGraphBackward(graph, n):
Create cost[n+1] ← ∞ // Minimum cost from each vertex to destination
Create path[n+1] ← -1 // To track the shortest path
cost[n] ← 0 // Cost at the destination node is 0
for i ← n - 1 to 1 step -1:
for each neighbor j of i:
if graph[i][j] ≠ 0 and graph[i][j] + cost[j] < cost[i]:
cost[i] ← graph[i][j] + cost[j]
path[i] ← j
PrintShortestPath(path, 1, cost[1])

2. PrintShortestPath(path, source, minCost):


print "Shortest Path: "
node ← source
while node ≠ -1:
print node
node ← path[node]
print "Minimum Cost: " minCost

You might also like