cs3401 Algorithms Lab Manual Final
cs3401 Algorithms Lab Manual Final
LISTOFEXPERIMENTS
SearchingandSortingAlgorithms
Implement Linear Search. Determine the time required to search for an element. Repeat the experiment for
differentvaluesofn,thenumberofelementsinthelisttobesearchedandplotagraphofthetimetakenversus n.
ImplementrecursiveBinarySearch.Determinethetimerequiredtosearchanelement.Repeattheexperiment for different values
of n, the number of elements in the list to be searched and plot a graph of the time taken versus n.
Givenatexttxt[0...n-1]andapatternpat[0...m-1],writeafunctionsearch(charpat[],chartxt[])thatprints all occurrences of pat [ ]
in txt [ ]. You may assume that n > m.
SortagivensetofelementsusingtheInsertionsortandHeapsortmethodsanddeterminethetimerequired to sort the elements.
Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the
time taken versus n.
GraphAlgorithms
DevelopaprogramtoimplementgraphtraversalusingBreadthFirstSearch
DevelopaprogramtoimplementgraphtraversalusingDepthFirstSearch
Fromagivenvertexinaweightedconnectedgraph,developaprogramtofindtheshortestpathstoother vertices using Dijkstra‟s
algorithm.
FindtheminimumcostspanningtreeofagivenundirectedgraphusingPrim‟salgorithm.
ImplementFloyd‟salgorithmfortheAll-Pairs-Shortest-Pathsproblem.
ComputethetransitiveclosureofagivendirectedgraphusingWarshall'salgorithm. Algorithm Design Techniques
Developaprogramtofindoutthemaximumandminimumnumbersinagivenlistofnnumbersusingthe divide and conquer
technique.
Implement Merge sort and Quick sort methods to sort an array of elements and determine the time required
tosort.Repeattheexperimentfordifferentvaluesofn,thenumberofelementsinthelisttobesortedandplota graph of the time
taken versus n.
StateSpaceSearchAlgorithms
ImplementNQueensproblemusingBacktracking.
Searching and Sorting Algorithms
1.Implement Linear Search. Determine the time required to search for an element. Repeat the experiment for
different values of n, the number of elements in the list to be searched and plot a graph of the time taken versus n.
Aim:
To Implement Linear Search and to determine the time required to search for an element ,the Number of elements in the
list to be searched and plot a graph of the time take n versus n.
Algorithm:
Step1:First,read the search element (Target element)in the array.
Step2:Set an integer i=0andrepeat steps3to 4 till I reaches the end of the array.
Step 3: Match the key with arr[i].
Step4:Ifthekeymatches,returntheindex.Otherwise, increment iby1.
Program:
#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
#define max 20
int pos;
int linsearch(int,int[],int);
void main()
{
Int ch=1;
doublet;
int n,i,a[max],k,op,low,high,pos;clock_t,begin,end;
clrscr();
while(ch)
{
printf(“\n MENU\n1.LinearSearch\n2.Exit\n”);
printf(“\nEnter Your choice\n”);
scanf(“%d”,&op);
switch(op)
{
Case1:printf(“\nEnter the Number ofE lements\n”);
scanf(“%d”,&n);
printf(“\nEntertheElementsofanArray\n”); for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“\nEntertheElement tobeSearched\n”);
scanf(“%d”,&k);
begin=clock();
pos=linsearch(n,a,k);
end=clock();
if(pos==-1)
printf(“\n\nUnsuccessfulSearch”);
else
printf(“Element%disfoundatposition%d”,k,pos+1);
printf(“\nTimeTakenis%fCPUCycles\n”,(end-begin)/CLK_TCK);
getch();
break;
default:printf(“InvalidChoiceEntered\n”);
exit(0);
}
printf(“\nDoyouwishtorunagain(1/0)\n”); scanf(“%d”,&ch);
}
getch();
}
Int linsearch(intn,inta[],intk)
{
delay(1000); if(n<0)return-1;
if(k==a[n-1])
return(n-1);
else
return linsearch(n-1,a,k);
}
Output:
Aim:
To implement recursive Binary Search and determine the time required to search an element.
Algorithm:
Step1:Find the middle element of array. using middle= initial_value+ end_value/2;
Step 2: If middle = element, return „element found‟ and index.
Step3:if middle>element,call the function with end_value=middle-1.
Step 4: if middle < element, call the function with start_value = middle + 1 .
Step 5 : exit.
Program:
#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
#define max 20int pos;
int binsearch(int,int[],int,int,int);
void main()
{
Int ch=1; doublet;
int n,i,a[max],k,op,low,high,pos, clock_t,begin,end;
clrscr();
while(ch)
{
printf("\n MENU\nl.BinarySearch\n2.Exit\n”);
printf("\nenteryourchoice\n");
scanf("%d",&op);
switch(op)
{
case1:printf("\nenter.thenumberofelements\n“);
scanf(“%d"&n);
priritf("\nentertheelementsinorder\n"); for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nentertheelementtobe searched\n”);
scanf("%d",&k); low=0;
high=n-1; begin=clock();
pos=binsearch(n,a,k,low,high);
end=clock();
if(pos==-1)
printf(“\n\nUnsuccessful Search”); else
printf("\nelement%disfoundatposition%d”,k,pos+1);
printf("\nTimeTakenis%fCPUcycles\n”,(end-begin)/CLK_TCK);
getch();
break;
}
printf(''\nDoyouwishtorunagain(l/0) \ n");
scanf("%d",&ch);
}
getch();
}
Int binsearch(int n,int a[],int k,int low,int high)
{
int mid; delay(1000); mid=(low+high)/2;
if(low>high) return -1; if(k==a[mid]) return(mid);
elseif(k<a[mid])
return binsearch(n,a,k,low,mid-1);
else
return binsearch(n,a,k,lmid+1,high);
}
Output:
***********MENU************
1.BinarySearch 2.Exit
Enter Your
Choice1
Entert henumber of e lements 3
Enterthenumberofanarrayinthe
order98
22
46
Enter the elements to be searched 22
Element 22 is found at position2
Time Taken is 1.978022 CPU cycles.
3.Given at ext txt[0...n-1] and a pattern pat[0...m-1],write a function search(char pat[],char
txt[ ]) that prints all occurrences of pat[] in txt[]. You may assume that n>m.
Aim:
To implement function search and to print all occurrences of the pattern in the given text.
Algorithm:
NAVE_STRING_MATCHING(T,P)
fori←0ton-mdo
ifP[1......m]==T[i+1. i+m]then
print"Match Found" end
Program:
#include <stdio.h>
#include<string.h>
Void search(char*pat,char*txt)
{
intM=strlen(pat); int N = strlen(txt);
for(inti=0;i<=N-M;i++)
{
int j;
for (j = 0; j < M; j++) if(txt[i+j]!=pat[j]) break;
if(j==M)
//ifpat[0...M-1]=txt[i,i+1, i+M-1]
printf("Patternfoundatindex%d\n",i);
}
}
intmain()
{chartxt[]="AABAACAADAABAAABAA";
char pat[] = "AABA"; search(pat, txt);
return 0;
}
OUTPUT:
Pattern found at index 0
Pattern found at index 9
Pattern found at index 12
4.Sort a given set of elements using the Insertion sort and Heap sort methods and determine the time
requiredtosorttheelements.Repeattheexperimentfordifferentvaluesof n,the number of elementsin the list to be sorted
and plot a graph of the time taken versus n.
Aim:
To sort the elements using insertions or and heap sort.
Algorithm:
Insertion Sort:
Step1:Iftheelement is the first one,it is already sorted. Step 2 : Move to next element.
Step3:Comparethecurrentelement with all elements in the sorted array.
Step4:If the element in the sorted array is smaller tan the current element, iteratet the nexte lement. Otherwise, shift all the
greater element in the array by one position towards the right
Step 5 : Insert the value at the correct position.
Step 6 :Repeat until the complete list is sorted.
Program:
#include<stdio.h>
Void insert(inta[],int n)
{
inti, j,temp;
for(i=1;i<n;i++){ temp = a[i];
j=i -1;
while(j>=0&&temp<= a[j])
{
a[j+1]=a[j]; j = j-1;
}
a[j+1]=temp;
}
}
voidprintArr(inta[],int n)
{
Int i;
for (i = 0; i < n; i++) printf("%d",a[i]);
}
Int main()
{
Int a[20];
int n = sizeof(a) / sizeof(a[0]); printf(“enternumberofelements:”); scanf(“%d”,&n);
printf(“entertheelements”); for(int i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf("Beforesortingarrayelementsare-\n"); printArr(a, n);
insert(a,n);
printf("\nAftersortingarrayelementsare-\ n"); printArr(a, n);
return 0;
}
Output:
Before Sorting array elements are 12 31 25 8 32 17
After Sorting array elements are 8 12 17 25 31 32
HeapSort:
Algorithm:
Step1: Buildabinary heap.
Step2:Startiteratingfrommidtothestartofthebinaryheaparray.
Step3:Oneveryiteration,swaptherootnodewiththelastleafnode.
Step4:Removetheleafnodebyputtingitbackattheendofthenewsortedarray. Step 5: Again do the heapify operation and repeat
the iteration from step 2.
Step6:Exit
#include<stdio.h>
// function
prototyping void
heapify(int*,int, int); void
heapsort(int*, int);
voidprint_array(int*,int);
intmain()
{
intarr[],CLK_TCK,end,start;
intn=sizeof(arr)/sizeof(arr[0]);
printf("enter no of elements");
scanf("%d",&n);
printf("enterele
ments"); for(int
i=0;i<n;i++)
scanf("%d",&arr[i]);
printf("\nArraybeforesorting:\n");
print_array(arr, n);
start=clock();
heapsort(arr,n);
end=clock();
printf("\nTimetakenbyHeapsortofCPUCycle”,(end-start)/CLK_TCK); getch();
return0;
}
/*sortsthegivenarrayofnsize*/
voidheapsort(int*arr,intn)
{
//buildthebinarymaxheap
for(inti =n /2 -1;i >= 0;i--)
{
heapify(arr,n,i);
}
//sortthemaxheap
for(inti =n- 1;i >= 0;i--)
{
//swaptherootnodeandthelastleafnode
inttemp=arr[i]; arr[i] = arr[0]; arr[0] = temp;
//againheapifythemaxheapfromtheroot
heapify(arr,i,0);
}
}
/*heapifythesubtreewithrooti*/
voidheapify(int*arr,intn,inti)
{
//storelargestastheroot element
intlargest=i;
//nowcheckwhethertherightandleftrightislargerthantherootornot
if(left<n&&arr[left]>arr[largest])
{
largest=left;
}
if(right<n&&arr[right]>arr[largest])
{
largest=right;
}
//iftherootissmallerthanthechildrenthenswapitwiththelargestchildren'svalue
if(largest!=i)
{
int temp =
arr[i];
arr[i]=arr[largest];
arr[largest]=temp;
//againheapifythatsideoftheheapwheretheroothasgone
heapify(arr,n,largest);
}
}
/*printfthearray*/
voidprint_array(int*arr,intn)
{
for(inti =0;i <n;i++)
{
printf("%d",arr[i]);
}
}
Output:
EnterthenumberofElements:3
Enter the 3 Elements:
42
85
58
SortedElementsare 42 58 85
Time taken by Heapsor t0.109890CPUCycle.
GraphAlgorithms
5.Develop a program to implement graph traversal using Breadth First Search.
Aim:
To Develop a program to implement graph traversal using Breadth First Search.
Algorithm:
o First take the number of nodes in the graph as input and then create an adjacency matrix ofsize n x n where n
is the number of nodes in the graph.
o Next take the adjacency matrix as input.
o Take the starting node as input.
o We then call the bfs function with the starting node as the argument.
o In the bfs function, we first mark the current node as visited and then we enqueue all the nodes which are
adjacent to the current node and are not visited.
o Wethendequeueanodefromthequeueandcallthebfsfunctionwiththedequeuednodeasthe argument.
o We repeat the above steps untilt he queue is empty.
o Finally,we print the nodes which are reachable from the starting node.
Program:
#include<stdio.h>
Int n,i,j,visited[10],queue[10],front=-1,rear=-1;
int adj[10][10];
voidbfs(int v)
{
for (i=1; i<=n;i++)
if(adj[v][i]&&!visited[i]) queue[++rear] = i;
if(front<=rear)
{
visited[queue[front]]=1; bfs(queue[front++]);
}
}
void main()
{
intv;
printf("Enterthenumberofvertices:");
scanf("%d",&n);
for (i=1; i<=n;i++)
{
queue[i]=0;
visited[i]=0;
}
printf("Entergraphdatainmatrixform:\n"); for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++) scanf("%d",&adj[i][j]);
printf("Enterthestartingvertex:"); scanf("%d", &v);
bfs(v);
printf("Thenodewhicharereachableare:\n"); for (i = 1; i <= n; i++)
if (visited[i]) printf("%d\t",i);
else
printf("BFSisnotpossible.Notallnodesarereachable"); return 0;
}
Output:
intmain()
{
intgraph[V][V] ={{0,4,0,0,0,0,0,8,0},
{4,0,8,0,0,0,0,11,0 },
{0,8,0,7, 0,4,0,0,2 },
{0,0,7,0,9,14,0,0,0 },
{0,0,0,9,0,10,0,0,0 },
{0,0,4,14,10,0,2,0,0},
{0,0,0,0, 0,2,0,1,6 },
{8,11,0,0,0,0,1,0,7 },
{0,0,2, 0,0,0,6, 7,0} };
dijkstra(graph,0);
return 0;
}
OUTPUT:
: Distance from source to vertex
0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14
8.Find the minimum cost spanning tree of a given undirected graph using Prim’s algorithm.
Aim:
To Find the minimum costs panning tree of a given undirected graph using Prim‟s algorithm.
Algorithm:
Step1:Determine an arbitrary vertex as the starting vertex of the MST.
Step2:Follow steps3to5tillthereareverticesthatarenotincludedintheMST(knownasfringe vertex).
Step3:Find edges connecting any tree vertex with the fringe vertices.
Step 4: Find the minimum among these edges.
Step5:Add the chosen edge to the MST if it does not for many cycle.
Step 6: Return the MST and exit.
Program:
#include <limits.h>
#include<stdbool.h>
#include <stdio.h>
#define V 5
Int minKey(intkey[],boolmstSet[])
{
intmin=INT_MAX,min_index;for (int v = 0; v < V; v++)
if(mstSet[v]==false&&key[v]<min) min = key[v], min_index = v;
returnmin_index;
}
intprintMST(intparent[],intgraph[V][V])
{
printf("Edge\tWeight\n"); for (int i = 1; i < V; i++)
printf("%d-%d\t%d\n",parent[i], i, graph[i][parent[i]]);
}
voidprimMST(intgraph[V][V])
{
intparent[V]; int key[V];
boolmstSet[V];
for(inti=0;i<V; i++)
key[i]=INT_MAX,mstSet[i]=false; key[0] = 0;
parent[0]=-1;
for(intcount =0;count<V-1;count++)
{
intu=minKey(key,mstSet); mstSet[u] = true;
for (intv=0;v<V; v++)
if(graph[u][v]&&mstSet[v]==false && graph[u][v] < key[v])parent[v]=u,key[v]=graph[u][v];
}
printMST(parent,graph);
}
intmain()
{
intgraph[V][V]={{0,2,0,6,0},
{2,0, 3,8,5 },
{0,3, 0,0,7 },
{6,8, 0,0,9 },
{0,5, 7,9, 0}
};
primMST(graph);
return 0;
}
Output: Edge Weight
0-1 2
1-2 3
0-2 6
1-3 5
9.Implement Floyd’s algorithm for the All-Pairs-Shortest-Paths problem.
Aim :
To implement Floyd‟s algorithm for the All-Pairs-Shortest-Paths problem.
Algorithm:
Step1:Initializetheshortestpathsbetweenany2verticeswithInfinity.
Step 2: Find all pair shortest paths that use 0 intermediate vertices, then find the shortest paths that use 1 intermediate vertex
and so on. until using all N vertices as intermediate nodes.
Step3:Minimizetheshortest pathsbetweenany2 pairs in the previous operation.
Step 4:For any 2vertices(i,j),one should actually minimize the distances between this pair using the first K
nodes,so the shortest path will be: min(dist[i][k]+dist[k][j],dist[i][j]).dist[i][k]representstheshortest path that only uses the first
K vertices, dist[k][j] represents the shortest path between the pair k,j.
As the shortest path will be a concatenation of the shortest path from I tok,then from k to j.
Program:
#include<bits/stdc++.h>
usingnamespacestd;
#define V 4
voidprintSolution(intdist[][V]); voidfloydWarshall(intdist[][V])
{
inti,j,k;
for(k=0; k<V; k++)
{
for(i=0; i<V; i++)
{
for (j =0; j <V; j++)
{
if(dist[i][j]>(dist[i][k]+dist[k][j])&&(dist[k][j]!=INF&&dist[i][k]!=INF)) dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
printSolution(dist);
}
voidprintSolution(intdist[][V])
{
cout<<"Thefollowingmatrixshowstheshortest""distances""betweeneverypairofvertices\n";for (int i = 0; i < V; i++)
{
for (intj =0;j <V; j++)
{
if(dist[i][j]==INF)
cout<<"INF"<<"";
else
cout<<dist[i][j]<<"";
}
cout<<endl;
}
}
intmain()
{
intgraph[V][V]={{0,5,INF,10},{INF,0,3,INF},{INF,INF,0,1},{INF,INF,INF,0}};
floydWarshall(graph); return 0;
}
Output:
The following matrix shows the shortest distance between every pair of vertices.
0 5 8 9
INF 0 3 4
INF INF 0 1
INF INF INF 0
10.Compute the transitive closure of a given directed graph using Warshall's algorithm.
Aim :
To Compute the transitive closure of a given directed graph usingWarshall's algorithm.
Algorithm:
Step1:CreateamatrixA0ofdimensionn*n where n is the number of vertices. ...
Step 2:Now, create a matrix A1 using matrix A0 . ...
Step 3 :Similarly, A2 is created using A1 . ...
Step4:Similarly,A3andA4isalsocreated....
Step5:A4 gives the shortest path between a ch pair of vertices.
Program:
#include<stdio.h>
#include<conio.h>
int n,a[10][10],p[10][10];
void path()
{
int i,j,k; for(i=0;i<n;i++) for(j=0;j<n;j++) p[i][j]=a[i][j]; for(k=0;k<n;k++) for(i=0;i<n;i++) for(j=0;j<n;j++)
if(p[i][k]==1&&p[k][j]==1)p[i][j]=1;
}
void main()
{
int i,j; clrscr();
printf("Enterthenumberofnodes:"); scanf("%d",&n);
printf("\nEntertheadjacencymatrix:\ n"); for(i=0;i<n;i++)
for(j=0;j<n;j++) scanf("%d",&a[i][j]); path();
printf("\nThepathmatrixisshowmbelow\ n"); for(i=0;i<n;i++)
{
for(j=0;j<n;j++) printf("%d",p[i][j]); printf("\n");
}
getch();
}
Output:
Enterthenumberofnodes:4
0 1 0 0
0 0 0 1
0 0 0 0
1 0 1 0
The path matrix is shown below
1 1 1 1
1 1 1 1
0 0 0 0
1 1 1 1
Algorithm Design Techniques
11.Develop a program to find out the maximum and minimum numbers in a given list of n
Numbers using the divide and conquer technique.
Aim:
To develop a C program to find out the maximum and minimum numbers in a given list of n
Numbers using the divide and conquer technique.
Algorithm:
o Set min and max to arr[0]
o Startloopat1,usingindexi
o Check ifarr[i]<min; if so,set minto arr[i]
o Check ifarr[i]>max; if so,setmax to arr[i]
o At end of loop, respond with an array containing[min,max]
o If the arrayis1element long,r eturn[arr[0],arr[0]]
o If the arrayis2elementslong
o Ifarr[0]>arr[1],return[arr[1],arr[0]] ii.Otherwise, return arr
o Split the array roughly into a left half and right half, calling min max one ach half
o return[min(left[0],right[0]),max(left[1],right[1]]
Program:
#include<stdio.h>
#include<stdio.h>
int max, min;
inta[100];
voidmaxmin(inti,intj)
{
intmax1,min1,mid; if(i==j)
{
max=min=a[i];
}
else
{
if(i==j-1)
{
if(a[i]<a[j])
{
max=a[j];
min=a[i];
}
else
{
max=a[i];
min=a[j];
}
}
else
{
mid = (i+j)/2; maxmin(i,mid);
max1=max; min1 =min; maxmin(mid+1,j);if(max
<max1)
max = max1; if(min>min1) min = min1;
}
}
}
intmain()
{
inti,num;
printf("\nEnterthetotalnumberofnumbers: "); scanf ("%d",&num);
printf("Enterthenumbers:\n"); for(i=1;i<=num;i++)
scanf("%d",&a[i]);
max=a[0];
min = a[0]; maxmin(1,num);
printf("Minimum element in an array:%d\n",min);
printf("Maximum element in an array:%d\n",max); return 0;
}
Output:
Enter the total number of numbers: 72
88
82
85
65
Minimum element in an array : 72
Maximum element in an array:82
12.Implement Merge sort and Quick sort methods to sort an array of elements and determine the time required to
sort. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph
of the time taken versus n.
Aim:
To write a C program to Implement Merge sort and Quick sort methods to sort an array of elements and determine the time
required to sort.
Algorithm:
Step1: Findthe middle indexofthe array. Middle = 1 + (last – first)/2
Step2:Divide thearrayfromthemiddle.
Step3: Call mergesort for the first halfofthearray MergeSort(array, first, middle)
Step4: Call mergesort for thesecond halfofthe array.MergeSort(array, middle+1, last)
Step5: Mergethetwo sortedhalves into asingle sortedarray. Merge Sort:
step1:start
step2:declarearrayandleft,right,midvariable step 3: perform merge function.
ifleft>right return
mid= (left+right)/2 mergesort(array,left,mid)
mergesort(array,mid+1,right) merge(array, left, mid, right)
step4:Stop
Program:
#include<stdio.h>
#include<time.h>
/*Functiontomergethesubarraysofa[]*/ void merge(int a[], int beg, int mid, int end)
{
inti,j,k;
intn1=mid-beg+1; int n2 = end - mid;
intLeftArray[n1],RightArray[n2];//temporaryarrays
while(j<n2)
{
a[k]=RightArray[j]; j++;
k++;
}
}
voidmergeSort(inta[],intbeg,intend)
{
if(beg <end)
{
int mid = (beg + end) / 2; mergeSort(a, beg, mid); mergeSort(a,mid+1,end); merge(a, beg, mid, end);
}
}
+
/*Functiontoprintthearray*/ void printArray(int a[], int n)
{
inti;
for (i = 0; i < n; i++) printf("%d",a[i]);
printf("\n");
}
intmain()
{
inta[]={12,31,25,8,32,17,40,42},clock_t,end,begin; int n = sizeof(a) / sizeof(a[0]);
printf("Beforesortingarrayelementsare-\n"); printArray(a, n);
//begin=clock(); mergeSort(a,0,n-1);
printf("Aftersortingarrayelementsare-\n"); printArray(a, n);
//end=clock();
//printf(“timetakenof%fcycles”,(end-begin)/CLK_TK); return 0;
}
Output:
Given array is 12 11 13 5 6 7
Sorted array is 5 6 7 11 12 13
Quick Sort:
Algortihm:
Step1:Consider the first element of the list as pivot(i.e.,Element at first position in the list).
Step2: Define two variables I and j. Set I andjto first and last elements of the list respectively.
Step3: Increment i until list[i] > pivot then stop.
Step4:Decrement j until list[j]<pivot then stop.
Step 5 : If i < j then exchange list[i] and list[j].
Step6:Repeatsteps3,4 &5until i>j.
Step7:Exchange the pivot element with list[j] element.
Program:
#include<stdio.h>
#include<conio.h>
Void quickSort(int[10],int,int); void main(){
Int list[20],size,i;
printf("Entersizeofthe list:");
scanf("%d",&size);
printf("Enter%dintegervalues:",size);
for(i = 0; i < size; i++)
scanf("%d",&list[i]); quickSort(list,0,size-1);
printf("Listaftersortingis:"); for(i=0;i<size;i++)
printf("%d",list[i]);
getch();
}
Void quickSort(int list[10],int first,int last)
{
int pivot,i,j,temp;
if(first<last)
{
pivot=first;
i =first;
j=last;
while(i < j)
{
while(list[i]<= list[pivot]&&i< last)
i++;
while(list[j]>list[pivot])
j--;
if(i<j){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
temp = list[pivot];
list[pivot] = list[j];
list[j] = temp;
quickSort(list,first,j-1);
quickSort(list,j+1,last);
}
}
Output:
Enter size of the list:8
Enter 8 integer values:5 3 8 1 4 6 2 7
List after sorting is:1 2 3 4 5 6 7 8
State Space Search Algorithms
13.Implement N Queens problem using Backtracking.
Aim:
To write a C program to Implement N Queens problem using Backtracking.
Algorithm:
Step1:Place the queen row-wise, starting from the left-most cell.
Step2:If all queens are placed then return true and print the solution matrix.
Step 3 : Else try all columns in the current row.
Condition 1 : Check if the queen can be placed safely in this column then mark the current cell [Row, Column]in the solution
matrix as 1 and try to check the rest of the problem recursively byplacing the queen here leads to a solution or not.
Condition 2 : If placing the queen [Row, Column] can lead to the solution return true and printthe solution for each queen's
position.
Condition 3 : If placing the queen cannot lead to the solution then unmark this [row, column] in the solution matrix as 0,
BACKTRACK, and go back to condition 1 to try other rows.
Step4:Ifalltherowshavebeentriedandnothing worked,returnfalsetotriggerbacktracking.
Program:
#include <bits/stdc++.h>
#define N 4
usingnamespacestd;
voidprintSolution(intboard[N][N])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
if(board[i][j]) cout<<"Q"; else cout<<". ";
printf("\n");
}
}
boolisSafe(intboard[N][N],introw,intcol)
{
Int i,j;
for(i=0;i<col;i++)
if (board[row][i])
return false;
for(i=row,j=col;i>=0&&j>=0;i--,j--)
if (board[i][j])
return false;
for(i=row,j=col;j>=0&&i<N;i++,j--)
if (board[i][j])
return false;
return true;
}
boolsolveNQUtil(intboard[N][N],intcol)
{
if(col>=N)
return true;
for(inti=0;i<N;i++)
{
if (isSafe(board, i, col))
{
board[i][col]=1;
if(solveNQUtil(board,col+1))
return true;
board[i][col]=0;//BACKTRACK
}
}
Return false;
}
boolsolveNQ()
{
Int board[N][N]={{0,0,0,0},{0,0,0,0},{0,0,0,0},{ 0,0,0,0}};
if(solveNQUtil(board,0)==false)
{
cout<<"Solutiondoesnotexist"; return false;
}
printSolution(board); return true;
}
intmain()
{
solveNQ();
return 0;
}
Output:
..Q.
Q...
...Q
.Q..
Approximation Algorithms Randomized Algorithms
14.Implement any scheme to find the optima lsolution for theTraveling Sales person problem and then solve the same
problem instance using any approximation algorithm and determine the error in the approximation.
Aim:
To find the solution usingTraveling Sales person Problem and determine the error in the approximation.
Algorithm:
Step1:Considercity1asthestartingandendingpoint.Sincetherouteiscyclic,wecanconsideranypointas a starting point.
Step2:Generateall(n-1)!permutationsofcities.
Step3:Calculatethecostofeverypermutationandkeeptrackoftheminimumcostpermutation. Return the permutation with
minimum cost.
Program:
#include <bits/stdc++.h>
using namespace std;
#define V 4
Int travllingSalesmanProblem(intgraph[][V],ints)
{
vector<int>vertex;
for(inti=0;i<V;i++) if (i != s)
vertex.push_back(i); intmin_path=INT_MAX;do
{
intcurrent_pathweight=0; int k = s;
for (int i = 0; i < vertex.size(); i++) { current_pathweight+=graph[k][vertex[i]]; k = vertex[i];
}
current_pathweight +=graph[k][s];
min_path=min(min_path,current_pathweight);
}while(
next_permutation(vertex.begin(), vertex.end())); return min_path;
}
intmain()
{
//matrixrepresentationofgraph int graph[][V] = { { 0, 10, 15, 20 },
{10,0,35,25 },
{15,35,0,30 },
{20,25,30,0}};
ints = 0;
cout<<travllingSalesmanProblem(graph,s)<<endl;
return 0;
}
Output:
80
15.Implement randomized algorithms for finding the kth smallest number. The programs can be implemented in
C/C++/JAVA/ Python.
Aim:
To Implement randomized algorithms for finding the kth smallest number.
Algorithm:
Step1:PartitionthearrayA[left..right]intotwosubarraysA[left..pos]andA[pos+1..right]suchthateach element of A[left .. pos] is
less than each element of A[pos + 1 .. right].
Step2:ComputesthenumberofelementsinthesubarrayA[left..pos]i.e.count=pos-left+1if(count==K), then A[pos] is the Kth
smallest element.
Step3:OtherwisedeterminesinwhichofthetwosubarraysA[left..pos-1]andA[pos+1..right]theKth smallest element lies.
Step4:If(count>K)thenthedesiredelementliesontheleftsideofthepartition.
Step 5: If (count < K), then the desired element lies on the right side of the partition. Since we already know i
valuesthataresmallerthanthekthsmallestelementofA[left..right],thedesiredelementisthe(K-count)th smallest element of A[pos
+ 1 .. right].
Step6:Basecaseisthescenarioofsingleelementarrayi.eleft==right.returnA[left]orA[right].
Program:
#include<stdio.h>
#include<conio.h>
Int cmpfunc(constvoid*a,constvoid* b)
{
return(*(int*)a-*(int*)b);
}
Int kthSmallest(intarr[],intN,int K)
{
qsort(arr,N,sizeof(int),cmpfunc); return arr[K - 1];
}
intmain()
{
Int arr[]={12,3,5,7,19};
int N=sizeof(arr)/sizeof(arr[0]),K=2;
printf("K'thsmallestelementis%d",kthSmallest(arr,N,K));
return 0;
}
4. A dummy node of the decision tree is created and enqueued to Q. The dummy node's profit and weight are 0.
b. Compute the next level node's profit. If it is greater than maxProfit, maxProfit must be
updated
c. Compute the next level node's bound. If it is greater than maxProfit, the next level node must
be added to Q
d. Consider a case where the next level node is not included in the solution – a node should be
added to the queue with the level set as next but without considering the weight and profit.
Program:
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
typedef enum { NO, YES } BOOL;
int N;
int vals[100];
int wts[100];
int cap = 0;
int mval = 0;
void getWeightAndValue (BOOL incl[N], int *weight, int *value) {
int i, w = 0, v = 0;
for (i = 0; i < N; ++i) {
if (incl[i]) {
w += wts[i];
v += vals[i];
}
}
*weight = w;
*value = v;
}
void printSubset (BOOL incl[N]) {
int i;
int val = 0;
printf("Included = { ");
for (i = 0; i < N; ++i) {
if (incl[i]) {
printf("%d ", wts[i]);
val += vals[i];
}
}
printf("}; Total value = %d\n", val);
}
void findKnapsack (BOOL incl[N], int i) {
int cwt, cval;
getWeightAndValue(incl, &cwt, &cval);
if (cwt <= cap) {
if (cval > mval) {
printSubset(incl);
mval = cval;
}
}
if (i == N || cwt >= cap) {
return;
}
int x = wts[i];
BOOL use[N], nouse[N];
memcpy(use, incl, sizeof(use));
memcpy(nouse, incl, sizeof(nouse));
use[i] = YES;
nouse[i] = NO;
findKnapsack(use, i+1);
findKnapsack(nouse, i+1);
}
int main(int argc, char const * argv[]) {
printf("Enter the number of elements: ");
scanf(" %d", &N);
BOOL incl[N];
int i;
for (i = 0; i < N; ++i) {
printf("Enter weight and value for element %d: ", i+1);
scanf(" %d %d", &wts[i], &vals[i]);
incl[i] = NO;
}
printf("Enter knapsack capacity: ");
scanf(" %d", &cap);
findKnapsack(incl, 0);
return 0;
}
Output:
/**
input:
4
1 15
5 10
39
45
8
output:
Included = { 1 }; Total value = 15
Included = { 1 5 }; Total value = 25
Included = { 1 3 4 }; Total value = 29