0% found this document useful (0 votes)
23 views32 pages

Advance Algorithm Lab Record

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
23 views32 pages

Advance Algorithm Lab Record

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 32

CERTIFICATE

This is to certify that Mr. MD NADEEM NOORI Bearing Roll NO


21MTCS031HY has satisfactory completed the course of
experiments in Advanced Algorithm prescribed by Maulana Azad
National Urdu University for the M.Tech First Year and First
Semester class in the Department of Computer Science &
Information Technology During the Academic year 2022.

Head
Department of CS & IT

Internal External
Examiner Examiner
INDEX
S.No Name of the Program Page Date Remarks
No.

1 Write a program to implement 4-5 12/11/2021


the Quick Sort

2 Write a program to implement 6-7 29/11/2021


the Heap Sort

3 Write a program to implement 8-9 03/12/2021


the Shaker/Cocktail Sort

4 Write a program to implement 10 - 11 17/12/2021


The Counting Sort

5 Write a program to implement 12 - 13 23/12/2021


the MST using Prim’s Algorithm

6 Write a program to implement 14 -15 23/12/2021


the Bellman-Ford Algorithm

7 Write a program to implement 16 - 17 12/01/2022


the Longest Common
Sequence(LCS) Problem

8 Write a program to implement 18 - 19 12/01/2022


the Pattern Matching using
Naive Algorithm
9 Write a program to implement 20 - 21 21/01/2022
Traveling SalesPerson (TSP)
Problem

10 22 - 24 21/01/2022
Write a program to implement
Tarjan's Algorithm

11 Write a program to implement Rabin 25 - 26 21/01/2022


Karp Pattern Matching Algorithm

12 Write a program to implement Knuth 27 - 29 28/01/2022


Morris

13 Write a program to implement 30 - 32 28/01/2022


Boyer-Moore algorithm
1.Write a program to implement the QUICK SORT:
#include <iostream>
using namespace std;
void swap(int *a, int *b)
{
int t = *a;//swapping operation
*a = *b;
*b = t;
}
void printArray(int array[], int size)
{
for (int i = 0; i < size; i++)
cout << array[i] << " ";
cout << endl;
}
int partition(int array[], int low, int high)
{
int pivot = array[high];
int i = (low - 1);
for (int j = low; j < high; j++)
{
if (array[j] <= pivot)
//if element at j position is small then swapp with i
{
i++;//if element at j position is greater then increment
swap(&array[i], &array[j]);
}
}// swap pivot with the greater element at i
swap(&array[i + 1], &array[high]);// return the partition point
return (i + 1);
}
void quickSort(int array[], int low, int high) {
if (low < high)
{
int pi = partition(array, low, high);
quickSort(array, low, pi - 1);
quickSort(array, pi + 1, high);
}
}
int main() {
int data[] = {8, 7, 4, 1, 0, 9, 20, 23, 17, 14};
int n = sizeof(data) / sizeof(data[0]);
cout << "Unsorted Array: \n";
printArray(data, n);// perform quicksort on data
quickSort(data, 0, n - 1);
cout << "Sorted array in ascending order: \n";
printArray(data, n);
}

SCREENSHOT:
2.Write a program to implement HEAP SORT:
source code:-
#include <iostream>
using namespace std;
void heapify(int arr[], int n, int i)
{
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
// Find largest among root, left child and right child
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
// Swap and continue heapifying
if (largest != i)
{
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
void heapSort(int arr[], int n) {
// FOR selecting array or index in which operation will
perform or will heapify .
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// Heap sort
for (int i = n - 1; i >= 0; i--)
{
swap(arr[0], arr[i]);
// Heapify root element to get highest element at root again
heapify(arr, i, 0);
}
}
// Print an array
void printArray(int arr[], int n) {
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << "\n";
}
int main() {
int arr[] = {1, 12, 9, 5, 6, 10};
//getting number of elements in array
int n = sizeof(arr) / sizeof(arr[0]);
heapSort(arr, n);
cout << "Sorted array is \n";
printArray(arr, n);
}
Min Heap output:
3.Shaker Sort / Bubble Sort Algorithm:
#include <iostream>
using namespace std;
void bubleSortshaker(int a[])
{
for(int i=0;i<5;i++)
{
for(int j=0;j<(5-i-1);j++)
{
if(a[j] > a[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}

int main()
{
int myarray[5]; //Hardcoded value as 5
cout<<"Enter 5 integer in random order:"<<endl;
for(int i=0;i<5;i++)
{
cin>>myarray[i];
}
cout<<"Before sorting"<<endl;
for(int i=0;i<5;i++)
{
cout<<myarray[i]<<" ";
}
bubleSortshaker(myarray);//sorting start/ function call
cout<<" "<<endl;
cout<<"After sorting"<<endl;
for(int i=0;i<5;i++)
{
cout<<myarray[i]<<" ";
}
return 0;
}

OUTPUT SCREEN:
4.COUNTING SORT:
#include <iostream>
using namespace std;
void countSort(int array[], int size)
{
int output[100];
int count[50];
int max = array[0];// Find the largest element of the array
for (int i = 1; i < size; i++)
{
if (array[i] > max)
max = array[i];
}
// Initialize count array with all zeros.
for (int i = 0; i <= max; ++i)
{
count[i] = 0;
}
// Store the count of each element
for (int i = 0; i < size; i++)
{
count[array[i]]++;
}// Store the cummulative count of each array
for (int i = 1; i <= max; i++)
{
count[i] += count[i - 1];
}
for (int i = size - 1; i >= 0; i--)
{
output[count[array[i]] - 1] = array[i];
count[array[i]]--;
}
for (int i = 0; i < size; i++)
{
array[i] = output[i];
}
}
void printArray(int array[], int size) {
for (int i = 0; i < size; i++)
cout << array[i] << " ";
cout << endl;
}//starting the source code
int main()
{
int array[] = {4, 32, 27, 55, 3, 3, 1};
int n = sizeof(array) / sizeof(array[0]);
countSort(array, n);
printArray(array, n);
}

SCREENSHOOT:
5. PRIM’S ALGORITHM USING C++
#include <bits/stdc++.h>
using namespace std;
#define V 6
int selectMinVertex(vector<int>& value, vector<bool>& setMST)
{
int minimum = INT_MAX;
int vertex;
for(int i=0;i<V;++i)
{
if(setMST[i]==false && value[i]<minimum)
{
vertex = i;
minimum = value[i];
}
}
return vertex;
}
void findMST(int graph[V][V])
{
int parent[V];
vector<int> value(V,INT_MAX);
vector<bool> setMST(V,false);
parent[0] = -1;
value[0] = 0;
for(int i=0;i<V-1;++i)
{
int U = selectMinVertex(value,setMST);
setMST[U] = true;
for(int j=0; j<V;++j)
{
if(graph[U][j]!=0 && setMST[j]==false && graph[U][j],value[j])
{
value[j]=graph[U][j];
parent[j] = U;
}
}
}
for(int i=1;i<V;++i)
cout<<"U->V: "<<parent[i]<<"->"<<i<<" wt = "<<graph[parent[i]][i]<<"\n";
}
int main()
{
int graph[V][V] = {{0, 4, 6, 0, 0, 0}, {4, 0, 6, 3, 4, 0}, {6, 6, 0, 1, 8, 0}, {0, 3, 1,
0, 2, 3}, {0, 4, 8, 2, 0, 7}, {0, 0, 0, 3, 7, 0}};
findMST(graph);
return 0;
}

OUTPUT:
6.Bellman - Ford's Algorithm
#include <bits/stdc++.h>
using namespace std;
void BellmanFord(int graph[][3], int V, int E,
int src)
{
// Initialize distance of all vertices as infinite.
int dis[V];
for (int i = 0; i < V; i++)
dis[i] = INT_MAX;
// initialize distance of source as 0
dis[src] = 0;
// Relax all edges |V| - 1 time. A simple shortest path from src to any other vertex can have at-most
|V| - 1 edges
for (int i = 0; i < V - 1; i++)
{
for (int j = 0; j < E; j++)
{
if (dis[graph[j][0]] != INT_MAX && dis[graph[j][0]] + graph[j][2] <
dis[graph[j][1]])
dis[graph[j][1]] =
dis[graph[j][0]] + graph[j][2];
}
}

// check for negative-weight cycles. The above step guarantees shortest distances if graph
doesn't contain negative weight cycle. If we get a shorter path, then there is a cycle.
for (int i = 0; i < E; i++)
{
int x = graph[i][0];
int y = graph[i][1];
int weight = graph[i][2];
if (dis[x] != INT_MAX && dis[x] + weight < dis[y])
cout << "Graph contains negative"
" weight cycle"
<< endl;
}

cout << "Vertex Distance from Source" << endl;


for (int i = 0; i < V; i++)
cout << i << "\t\t" << dis[i] << endl;
}
int main()
{
int V = 5; // Number of vertices in graph
int E = 8; // Number of edges in graph
// Every edge has three values (u, v, w) where the edge is from vertex u to v. And weight of the
edge is w.
int graph[][3] = { { 0, 1, -1 }, { 0, 2, 4 },
{ 1, 2, 3 }, { 1, 3, 2 },
{ 1, 4, 2 }, { 3, 2, 5 },
{ 3, 1, 1 }, { 4, 3, -3 } };

BellmanFord(graph, V, E, 0);
return 0;
}

OUTPUT SCREEN:-
7. LONGEST COMMON SEQUENCE:

#include <iostream>

#include<bits/stdc++.h>

using namespace std;

int dp[205][205][205];

int LCS(string &s1,string &s2,string &s3,int i,int j,int k)

if( i ==0 or j == 0 or k== 0)

return 0;

if(dp[i][j][k] != -1)

return dp[i][j][k];

if (s1[i-1] == s2[j-1] and s2[j-1] == s3[k-1])

return dp[i][j][k] = 1+LCS(s1,s2,s3,i-1,j-1,k-1);

int l = LCS(s1,s2,s3,i-1,j,k);

int r = LCS(s1,s2,s3,i,j-1,k);

int s = LCS(s1,s2,s3,i,j,k-1);

return max({l,r,s});

int main()
{

memset(dp,-1,sizeof(dp));

string s1;string s2;string s3;

cin>>s1;cin>>s2;cin>>s3;

cout << LCS(s1, s2, s3, s1.size(), s2.size(), s3.size());

return 0;

OUTPUT SCREEN:
8. Naive pattern searching algorithm
// C++ program for Naive Pattern
// Searching algorithm
#include <bits/stdc++.h>
using namespace std;

void search(char* pat, char* txt)


{
int M = strlen(pat);
int N = strlen(txt);

/* A loop to slide pat[] one by one */


for (int i = 0; i <= N - M; i++) {
int j;

/* For current index i, check for pattern match */


for (j = 0; j < M; j++)
if (txt[i + j] != pat[j])
break;

if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]


cout << "Pattern found at index "
<< i << endl;
}
}

// Driver Code
int main()
{
char txt[] = "AABAACAADAABAAABAA";
char pat[] = "AABA";
search(pat, txt);
return 0;
}
Output Screen:
9. TRAVELLING SALES PERSON
#include <iostream>
using namespace std;
#define INT_MAX 999999
int n=4;
int dp[16][4];
//adjacent matrix which defines the graph
int dist[10][10] {
{0,20,42,25},
{20,0,30,34},
{42,30,0,10},
{25,34,10,0}
};
//if all cities have been visited
int VISITED_ALL = (1<<n) - 1;
int tsp(int mask,int pos){
if(mask==VISITED_ALL){
return dist[pos][0];
}
//lookup
if(dp[mask][tsp]!=-1){
return dp[mask][pos];
}

int ans = INT_MAX;


//try to goto an unvisited city
for(int city=0;city<n;city++){
if(mask & (1<<city) == 0){
int newAns = dist[pos][city] + tsp( mask| (1 <<
city),city);
ans = min(ans,newAns);
}
}
return dp[mask][pos] = ans;
}
int main(){
for(int i=0;i,(1<<n);i++){
for(int j=0;j<n;j++){
dp[i][j]= -1;
cout<<tsp(1,0)<<endl;
return 0;
}
}

OUTPUT SCREEN:
10. TARJAN’S ALGORITHM SOURCE CODE:
#include <iostream>
#include <list>
#include <stack>

using namespace std;

class Graph {
int V;
list<int> *adj;
void fillOrder(int s, bool visitedV[], stack<int> &Stack);
void DFS(int s, bool visitedV[]);

public:
Graph(int V);
void addEdge(int s, int d);
void printSCC();
Graph transpose();
};

Graph::Graph(int V) {
this->V = V;
adj = new list<int>[V];
}
void Graph::DFS(int s, bool visitedV[]) {
visitedV[s] = true;
cout << s << " ";

list<int>::iterator i;
for (i = adj[s].begin(); i != adj[s].end(); ++i)
if (!visitedV[*i])
DFS(*i, visitedV);
}

// Transpose
Graph Graph::transpose() {
Graph g(V);
for (int s = 0; s < V; s++) {
list<int>::iterator i;
for (i = adj[s].begin(); i != adj[s].end(); ++i) {
g.adj[*i].push_back(s);
}
}
return g;
}

// Add edge into the graph


void Graph::addEdge(int s, int d) {
adj[s].push_back(d);
}

void Graph::fillOrder(int s, bool visitedV[], stack<int> &Stack) {


visitedV[s] = true;

list<int>::iterator i;
for (i = adj[s].begin(); i != adj[s].end(); ++i)
if (!visitedV[*i])
fillOrder(*i, visitedV, Stack);

Stack.push(s);
}

// Print strongly connected component


void Graph::printSCC() {
stack<int> Stack;

bool *visitedV = new bool[V];


for (int i = 0; i < V; i++)
visitedV[i] = false;

for (int i = 0; i < V; i++)


if (visitedV[i] == false)
fillOrder(i, visitedV, Stack);

Graph gr = transpose();

for (int i = 0; i < V; i++)


visitedV[i] = false;
while (Stack.empty() == false) {
int s = Stack.top();
Stack.pop();

if (visitedV[s] == false) {
gr.DFS(s, visitedV);
cout << endl;
}
}
}

int main() {
Graph g(8);
g.addEdge(0, 1);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(2, 4);
g.addEdge(3, 0);
g.addEdge(4, 5);
g.addEdge(5, 6);
g.addEdge(6, 4);
g.addEdge(6, 7);

cout << "Strongly Connected Components:\n";


g.printSCC();
}

OUTPUT SCREEN:-
11. RABIN KARP PATTERN MATCHING ALGORITHM
Source Code:
#include <string.h>
#include <iostream>
using namespace std;
#define d 10
void rabinKarp(char pattern[], char text[], int q) {
int m = strlen(pattern);
int n = strlen(text);
int i, j;
int p = 0;
int t = 0;
int h = 1;
for (i = 0; i < m - 1; i++)
h = (h * d) % q;
// Calculate hash value for pattern and text
for (i = 0; i < m; i++) {
p = (d * p + pattern[i]) % q;
t = (d * t + text[i]) % q;
}
// Find the match
for (i = 0; i <= n - m; i++) {
if (p == t) {
for (j = 0; j < m; j++) {
if (text[i + j] != pattern[j])
break;
}
if (j == m)
cout << "Pattern is found at position: " << i + 1 << endl;
}
if (i < n - m) {
t = (d * (t - text[i] * h) + text[i + m]) % q;
if (t < 0)
t = (t + q);
}
}
}
int main() {
char text[] = "ABCCDDAEFG";
char pattern[] = "CDD";
int q = 13;
rabinKarp(pattern, text, q);
}
Output screen:
12.Knuth Morris-Pratt Pattern Matching
Algorithm
#include <bits/stdc++.h>
void computeLPSArray(char* pat, int M, int* lps);
void KMPSearch(char* pat, char* txt)
{
int M = strlen(pat);
int N = strlen(txt);
int lps[M];

// Preprocess the pattern (calculate lps[] array)


computeLPSArray(pat, M, lps);

int i = 0; // index for txt[]


int j = 0; // index for pat[]
while (i < N) {
if (pat[j] == txt[i]) {
j++;
i++;
}

if (j == M) {
printf("Found pattern at index %d ", i - j);
j = lps[j - 1];
}

// mismatch after j matches


else if (i < N && pat[j] != txt[i]) {
// Do not match lps[0..lps[j-1]] characters,
// they will match anyway
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
}

// Fills lps[] for given patttern pat[0..M-1]


void computeLPSArray(char* pat, int M, int* lps)
{
// length of the previous longest prefix suffix
int len = 0;

lps[0] = 0; // lps[0] is always 0

// the loop calculates lps[i] for i = 1 to M-1


int i = 1;
while (i < M) {
if (pat[i] == pat[len]) {
len++;
lps[i] = len;
i++;
}
else // (pat[i] != pat[len])
{

if (len != 0) {
len = lps[len - 1];

}
else // if (len == 0)
{
lps[i] = 0;
i++;
}
}
}
}

// Driver program to test above function


int main()
{
char txt[] = "ABABDABACDABABCABAB";
char pat[] = "ABABCABAB";
KMPSearch(pat, txt);
return 0;
}

OUTPUT SCREEN:
13.BOYER-MOORE PATTERN SEARCHING ALGORITHM
#include <bits/stdc++.h>
using namespace std;
# define NO_OF_CHARS 256
void boyer( string str, int size,
int badchar[NO_OF_CHARS])
{
int i;

// Initialize all occurrences as -1


for (i = 0; i < NO_OF_CHARS; i++)
badchar[i] = -1;
for (i = 0; i < size; i++)
badchar[(int) str[i]] = i;
}
void search( string txt, string pat)
{
int m = pat.size();
int n = txt.size();

int badchar[NO_OF_CHARS];
boyer(pat, m, badchar);

int s = 0;
while(s <= (n - m))
{
int j = m - 1;
while(j >= 0 && pat[j] == txt[s + j])
j--;
if (j < 0)
{
cout << "pattern occurs at shift = " << s << endl;
s += (s + m < n)? m-badchar[txt[s + m]] : 1;

else

s += max(1, j - badchar[txt[s + j]]);


}
}

/* Driver code */
int main()
{
string txt= "ABAAABCD";
string pat = "ABC";
search(txt, pat);
return 0;
}

OUTPUT:

You might also like