0% found this document useful (0 votes)
3 views16 pages

Algorithm Unit 1

The document provides an overview of various algorithms including Prim's and Kruskal's for finding minimum spanning trees, several search algorithms like Linear, Binary, and Interpolation Search, and string matching algorithms such as Naive, Rabin-Karp, and KMP. It also covers sorting algorithms like Insertion Sort and Heap Sort, detailing their steps and pseudocode. Each algorithm is explained with its purpose, methodology, and implementation approach.

Uploaded by

Sneha.j Sneha.j
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)
3 views16 pages

Algorithm Unit 1

The document provides an overview of various algorithms including Prim's and Kruskal's for finding minimum spanning trees, several search algorithms like Linear, Binary, and Interpolation Search, and string matching algorithms such as Naive, Rabin-Karp, and KMP. It also covers sorting algorithms like Insertion Sort and Heap Sort, detailing their steps and pseudocode. Each algorithm is explained with its purpose, methodology, and implementation approach.

Uploaded by

Sneha.j Sneha.j
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/ 16

1.

PRIM’S ALGORITHM
Prim's Algorithm is a greedy algorithm that is used to find the
minimum spanning tree from a graph. Prim's algorithm finds the subset of
edges that includes every vertex of the graph such that the sum of the
weights of the edges can be minimized.

Prim's algorithm starts with the single node and explores all the
adjacent nodes with all the connecting edges at every step. The edges with
the minimal weights causing no cycles in the graph got selected.

Step 1: Determine an arbitrary vertex as the starting vertex of the MST.


Step 2: Follow steps 3 to 5 till there are vertices that are not included in
the MST (known as fringe vertex).
Step 3: Find edges connecting any tree vertex with the fringe vertices.
Step 4: Find the minimum among these edges.
Step 5: Add the chosen edge to the MST if it does not form any cycle.
Step 6: Return the MST and exit

PSEUDOCODE
prim(graph):
# Initialize an empty set to hold the vertices in the minimum spanning tree

mst = empty set


# Select the first vertex to start the tree
startVertex = first vertex in graph
mst.add(startVertex)
# Initialize the set of edges to consider
edges = edges connected to startVertex

# Iterate until all vertices are in the minimum spanning tree


while mst has fewer vertices than graph:
# Find the minimum edge in the set of edges
minEdge, minWeight = findMinEdge(edges)

# Add the vertex to the minimum spanning tree


mst.add(minEdge)

# Add the edges connected to the vertex to the set of edges to consider
for edge in edges connected to minEdge:
if edge is not in mst:
edges.add(edge)

# Remove the minimum edge from the set of edges to consider


edges.remove(minEdge)

# Return the minimum spanning tree as an array


return mst as an array

2.
3. KRUSKAL ALGORITHM
A minimum spanning tree (MST) or minimum weight
spanning tree for a weighted, connected, undirected graph
is a spanning tree with a weight less than or equal to the
weight of every other spanning tree.
Step 1: Sort all edges in increasing order of their edge weights.

Step 2: Pick the smallest edge.

Step 3: Check if the new edge creates a cycle or loop in a spanning tree.

Step 4: If it doesn’t form the cycle, then include that edge in MST.
Otherwise, discard it.

Step 5: Repeat from step 2 until it includes |V| - 1 edges in MST.

PSEUDOCODE

KRUSKAL(G):
A=∅
For each vertex v ∈ G.V:
MAKE-SET(v)
For each edge (u, v) ∈ G.E ordered by increasing order by weight(u, v):
if FIND-SET(u) ≠ FIND-SET(v):
A = A ∪ {(u, v)}
UNION(u, v)
return A

4. LINEAR SEARCH ALGORITHM


Linear Search is defined as a sequential search algorithm that
starts at one end and goes through each element of a list until
the desired element is found, otherwise the search continues till
the end of the data set.

STEP 1: Every element is considered as a potential match for


the key and checked for the same.

STEP 2: If any element is found equal to the key, the search is


successful and the index of that element is returned.

STEP 3 : If no element is found equal to the key, the search


yields “No match found”.
PSEUDOCODE

Start
linear_search ( array, value)

For each element in the array // loop the element till the size

If (searched element == value)return key

end if

end for

end

5. BINARY SEARCH ALGORITHM

Binary search follows the divide and conquer approach in which


the list is divided into two halves, and the item is compared with the
middle element of the list. If the match is found then, the location of
the middle element is returned. Otherwise, we search into either of
the halves depending upon the result produced through the match.

Step 1 − Select the middle item in the array and compare it with the key
value to be searched. If it is matched, return the position of the median.
Step 2 − If it does not match the key value, check if the key value is either
greater than or less than the median value.
Step 3 − If the key is greater, perform the search in the right sub-array; but
if the key is lower than the median value, perform the search in the left sub-
array.
Step 4 − Repeat Steps 1, 2 and 3 iteratively, until the size of sub-array
becomes 1.
Step 5 − If the key value does not exist in the array, then the algorithm
returns an unsuccessful search.

PSEUDOCODE
function binary_search(list, target):
left = 0
right = length(list) - 1
while left <= right:
mid = (left + right) // 2
if list[mid] == target:
return mid
elif list[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1

6. INTERPOLATION SEARCH ALGORITHM

Interpolation Search is a searching algorithm that uses an interpolation


formula to estimate the position of the target value in a sorted array or list.

Unlike binary search, which always selects the middle element, Interpolation
Search makes a more intelligent guess based on the distribution of the
data. It uses a formulaic approach to determine the position of the target
element within the array.
It is particularly effective when the elements are uniformly distributed.

STEP 1: Initialize low and high indices to the start and end of the array,
respectively.

STEP 2 :Calculate the probe position using the interpolation formula.

STEP 3 : Compare the probe element with the target element.

1. If they are equal, the search is successful.


2. If the probe element is greater, update the high index to the probe
position minus one.
3. If the probe element is smaller, update the low index to the probe
position plus one.

STEP 4 : Repeat steps 2-3 until the target element is found or the low
index exceeds the high index.
PSEUDOCODE

A → Array list
N → Size of A
X → Target Value

Procedure Interpolation_Search()

Set Lo → 0
Set Mid → -1
Set Hi → N-1

While X does not match


if Lo equals to Hi OR A[Lo] equals to A[Hi]
EXIT: Failure, Target not found
end if

Set Mid = Lo + ((Hi - Lo) / (A[Hi] - A[Lo])) * (X - A[Lo])

if A[Mid] = X
EXIT: Success, Target found at Mid
else
if A[Mid] < X
Set Lo to Mid+1
else if A[Mid] > X
Set Hi to Mid-1
end if
end if
End While
End Procedure

6. NAIVE-STRING-MATCHER (T, P)
The naive pattern searching algorithm does not require any pre-
processing phases. We can find substring by checking once for the string.
It also does not occupy extra space to perform the operation. If a match is
found, the end result of the pattern matching operation will be the index of
specified pattern, otherwise -1. Furthermore, this operation can return all
the indices if the desired pattern appears multiple times within the main
string.

1. n ← length [T]
2. m ← length [P]
3. for s ← 0 to n -m
4. do if P [1.....m] = T [s + 1....s + m]
5. then print "Pattern occurs with shift" s

7. RABIN-KARP ALGORITHM

In the Naive String Matching algorithm, we check whether every


substring of the text of the pattern’s size is equal to the pattern or
not one by one.
Like the Naive Algorithm, the Rabin-Karp algorithm also check
every substring. But unlike the Naive algorithm, the Rabin Karp
algorithm matches the hash value of the pattern with the hash
value of the current substring of text, and if the hash
values match then only it starts matching individual characters.
So Rabin Karp algorithm needs to calculate hash values for the
following strings.
 Pattern itself

 All the substrings of the text of length m which is the size of

pattern.

Step-by-step approach:

STEP 1: Initially calculate the hash value of the pattern.


STEP 2: Start iterating from the starting of the string:
STEP 3:Calculate the hash value of the current substring
having length m.
STEP 4 : If the hash value of the current substring and the
pattern are same check if the substring is same as the pattern.
STEP 5 :If they are same, store the starting index as a valid
answer. Otherwise, continue for the next substrings.
STEP 6 :Return the starting indices as the required answer.

RABIN-KARP-MATCHER (T, P, d, q)
1. n ← length [T]
2. m ← length [P]
3. h ← dm-1 mod q
4. p ← 0
5. t0 ← 0
6. for i ← 1 to m
7. do p ← (dp + P[i]) mod q
8. t0 ← (dt0+T [i]) mod q
9. for s ← 0 to n-m
10. do if p = ts
11. then if P [1.....m] = T [s+1.....s + m]
12. then "Pattern occurs with shift" s
13. If s < n-m
14. then ts+1 ← (d (ts-T [s+1]h)+T [s+m+1])mod q

8. THE KNUTH-MORRIS-PRATT (KMP) ALGORITHM

Knuth-Morris and Pratt introduce a linear time algorithm for the string
matching problem. A matching time of O (n) is achieved by avoiding
comparison with an element of 'S' that have previously been involved in
comparison with some element of the pattern 'p' to be matched. i.e.,
backtracking on the string 'S' never occurs

Components of KMP Algorithm:

1. The Prefix Function (Π): The Prefix Function, Π for a pattern encapsulates
knowledge about how the pattern matches against the shift of itself. This
information can be used to avoid a useless shift of the pattern 'p.' In other
words, this enables avoiding backtracking of the string 'S.'

2. The KMP Matcher: With string 'S,' pattern 'p' and prefix function 'Π' as
inputs, find the occurrence of 'p' in 'S' and returns the number of shifts of 'p'
after which occurrences are found.

COMPUTE- PREFIX- FUNCTION (P)

1. m ←length [P] //'p' pattern to be matched


2. Π [1] ← 0
3. k ← 0
4. for q ← 2 to m
5. do while k > 0 and P [k + 1] ≠ P [q]
6. do k ← Π [k]
7. If P [k + 1] = P [q]
8. then k← k + 1
9. Π [q] ← k
10. Return Π

9. INSERTION SORT ALGORITHM


Insertion sort is a very simple method to sort numbers in an ascending or descending
order. This method follows the incremental method. It can be compared with the
technique how cards are sorted at the time of playing a game.

This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained


which is always sorted. For example, the lower part of an array is maintained to be
sorted. An element which is to be 'inserted' in this sorted sub-list, has to find its
appropriate place and then it has to be inserted there. Hence the name, insertion sort.
The array is searched sequentially and unsorted items are moved and inserted into the
sorted sub-list (in the same array). This algorithm is not suitable for large data sets as
its average and worst case complexity are of Ο(n2), where n is the number of items.

Step 1 - If the element is the first element, assume that it is already sorted.
Return 1.

Step2 - Pick the next element, and store it separately in a key.

Step3 - Now, compare the key with all elements in the sorted array.

Step 4 - If the element in the sorted array is smaller than the current
element, then move to the next element. Else, shift greater elements in the
array towards the right.

Step 5 - Insert the value.

Step 6 - Repeat until the array is sorted.

PSEUDOCODE
function insertionSort(array)

for index from 1 to length(array)

key = array[index]

j = index - 1

while j >= 0 and array[j] > key

array[j + 1] = array[j]

j=j-1

array[j + 1] = key

10. Heap Sort Algorithm

Heap sort is a comparison-based sorting technique based on Binary Heap data


structure. It is similar to the selection sort where we first find the minimum element
and place the minimum element at the beginning. Repeat the same process for the
remaining elements.

 It is a data structure which is a complete binary tree


 All the levels are completely filled except the last level
 Heap has some order of values to be maintained between
parents and their children
 There are 2 variations of heap possible
MIN HEAP
Here the value of parent is always less than the value of its
children
Hence root will be the minimum in the entire heap
MAX HEAP
Here the value of parent is always more than the value of its
children
Hence root will be the maximum in the entire heap

STEPS

1. First, call build max heap to set the heap initially


2. Once the heap is created, take the root and wap it will the last
element of the heap
3. Reduce the size of the heap
4. Call max heapify of index 0 i.e, the new root of the heap
Heapsort(arr)
buildMaxHeap(arr)
for (int i = n - 1; i >= 0; i--) {

swap(&arr[0], &arr[i]);
heapsize--;
maxHeapify(arr,0);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy