You are on page 1of 21

LAB EXPERIMENT- 1

AIM

Write a Program for Iterative and Recursive Binary Search

INTRODUCTION

Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval
covering the whole array. If the value of the search key is less than the item in the middle of the
interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly
check until the value is found or the interval is empty.

ALGORITHM

ITERATIVE ALGORITHM

int find (ArrayList list, Double target)


// Iterative binary search will return the index of the target element, else list length
{
Boolean found = false;
int mid;
int first = 0;
int last = list.size( ) - 1;
while (first <= last && !found)
{
mid = (first + last) / 2;
if (list.get(mid).equals(target))
found = true;
else
if (list.get(mid) > target)
last = mid - 1;
else first = mid + 1;
}
if (found)
return mid;
return -1;
}

RECURSIVE ALGORITHM

int Find (ArrayList list, Double target, Double first, Double last)
// Recursive binary search will return the index of the target element, else list length
{
int mid;
if (first > last)
return -1;
mid = (first + last) / 2;
if (list.get(mid).equals(target))
return mid;
if (list.get(mid) < target)
return find(list, target, mid+1, last);
return find(list, target, first, mid-1);
}

PROGRAM

#include<stdio.h>
#include<conio.h>

void main()
{
int a[10],n,i,j,temp;
int beg,end,mid,target;
clrscr();
printf("enter the total numbers:?");
scanf("%d",&n);
printf("enter the array elements:?" );
for(i=0;i<n;i++)scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{

if(a[j+1]<a[j])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}

printf("the sorted numbers are:?");


for(i=0;i<n;i++)
printf("%4d",a[i]);
beg=a[0];
end=a[9];
mid=(beg+end)/2;
printf("\nenter the number to be searched:?");
scanf("%d",&target);

while(beg<=end && a[mid]!=target)


{
if(target<a[mid]) end=mid-1;else beg=mid+1;
mid=(beg+end)/2;}if(a[mid]==target)
{
printf("\nthe number is found at position %2d",mid);
}
else
{
printf("\nthe number is not found:");
}
getch();
}
LAB EXPERIMENT- 2

AIM

Write a program for Merge Sort

INTRODUCTION

Divide and Conquer


Divide and conquer is an important algorithm design paradigm based on multi branched
recursion. A divide and conquer algorithm works by recursively breaking down a problem into
two or more sub-problems of the same (or related) type, until these become simple enough to be
solved directly. The solutions to the sub-problems are then combined to give a solution to the
original problem.This technique is the basis of efficient algorithms for all kinds of problems,
such as sorting (e.g., quicksort, merge sort), multiplying large numbers (e.g Karatsuba), syntactic
analysis (e.g., top-down parsers), and computing the discrete Fourier transform (FFTs).

Merge sort
Merge sort is an O(n log n) comparison-based sorting algorithm. In most implementations it is
stable, meaning that it preserves the input order of equal elements in the sorted output. It is an
example of the divide and conquer algorithmic paradigm

ALGORITHM

Steps:
1. If the list is of length 0 or 1, then it is already sorted. Otherwise
2. Divide the unsorted list into two sublists of about half the size
3. Sort each sublist recursively by re-applying merge sort.
4. Merge the two sublists back into one sorted list

MERGE (A1, A2, A)


i.← j 1
A1[m+1], A2[n+1] ← INT_MAX
For k ←1 to m + n do
if A1[i] < A2[j]
then A[k] ← A1[i]
i ← i +1
else
A[k] ← A2[j]
j←j+1
MERGE_SORT (A)
A1[1 . . n/2] ← A[1 . . n/2]
A2[1 . . n/2] ← A[1 + n/2 . . n]
Merge Sort (A1)
Merge Sort (A1)
Merge Sort (A1, A2, A)

PROGRAM
// Merge Sort

#include <iostream.h>
#include<conio.h>
int a[20];
void merge(int,int,int);
void merge_sort(int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
merge_sort(low,mid);
merge_sort(mid+1,high);
merge(low,mid,high);
}
}
void merge(int low,int mid,int high)
{
int h,i,j,b[20],k;
h=low;
i=low;
j=mid+1;

while((h<=mid)&&(j<=high))
{
if(a[h]<=a[j])
{
b[i]=a[h];
h++;
}
else
{
b[i]=a[j];
j++;
}
i++;
}
if(h>mid)
{
for(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++) a[k]=b[k];
}
void main()
INTRODUCTION

Quicksort is a recursive sorting algorithm following the 'divide et impera' scheme. it takes an
element (token) of the list that is to sort and transfers every element that smaller on the one side
and everything that is bigger on the other. for the whole list, the algorithm is used on the two
parts again until the list is sorted.

ALGORITHM

procedure quicksort(array, left, right)


if right > left
select a pivot index //(e.g. pivotIndex := left+(right-left)/2)
pivotNewIndex := partition(array, left, right, pivotIndex)
quicksort(array, left, pivotNewIndex - 1)
quicksort(array, pivotNewIndex + 1, right)
function partition(array, left, right, pivotIndex)
pivotValue := array[pivotIndex]
swap array[pivotIndex] and array[right] // Move pivot to end
storeIndex := left
for i from left to right - 1 // left ≤ i < right
if array[i] ≤ pivotValue
swap array[i] and array[storeIndex]
storeIndex := storeIndex + 1
swap array[storeIndex] and array[right] // Move pivot to its final place
return storeIndex

PROGRAM

#include<iostream.h>
#include<conio.h>
int a[20];
void quicksort(int,int);
int partition(int,int);
void main()
{
int i,j,p,q,n,m;
clrscr();
cout<<"Enter the elents to sort";
cin>>q;
cout<<"Enter ("<<q<<") Numbers" <<endl;
for(i=0;i<q;i++)
{
cin>>a[i];
}
p=0;q=q-1;
n=p;m=q;
quicksort(n,m);
cout<<"Sorted Numbers Are"<<endl;
for(i=0;i<q+1;i++)
{
cout<<a[i];
}
getch();
}
void quicksort(int top, int bottom)
{
// top = subscript of beginning of array
// bottom = subscript of end of array

int middle;
if (top < bottom)
{
middle = partition(top, bottom);
quicksort(top, middle); // sort first section
quicksort(middle+1, bottom); // sort second section
}

}
//Function to determine the partitions
// partitions the array and returns the middle subscript
int partition(int top, int bottom)
{
int v = a[top];
int i = top;
int j = bottom + 1;
int temp;
do
{
do
{
j--;
}while (v<a[j]);

do
{
i++;
} while (v>a[i]);

if (i < j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}while (i < j);
a[top]=a[j];a[j]=v;
return j; // returns middle subscrip}

SAMPLE OUTPUT
LAB EXERCISE- 5

AIM

Write a program for Optimal Merge Patterns

INTRODUCTION

We want to merge some sorted files where the number of records are
{12,34,56,73,24,11,34,56,78,91,34,91,45}. What is the optimal way to merge them?

ALGORITHM:

At every stage we merge the files of the least length.

Steps:
Create a min heap of the set of elements.
While(heap has more than one element)
{
Delete a minimum element from the heap, and store it in min1;
Delete a minimum element from the heap, and store it in min2;
Create a node with the fields (info, left_link, right_ink);
Let info.node = min1 + min2;
Let left_link.node = min1;
Let right_link_node = min2;
Insert node with valued info into the heap;
}

struct treenode {
struct treenode *lchild, *rchild;
int weight;
};
typedef struct treenode Type;
Type *Tree(int n)
// list is a global list of n single node
// binary trees as described above.
{
for (int i=1; i<n; i++) {
Type *pt = new Type;
// Get a new tree node.
pt -> lchild = Least(list); // Merge two trees with
pt -> rchild = Least(list); // smallest lengths.
pt -> weight = (pt->lchild)->weight
+ (pt->rchild)->weight;
Insert(list, *pt);
}
return (Least(list)); // Tree left in l is the merge tree.
}

PROGRAM

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i,k,a[10],c[10],n,l;
cout<<"Enter the no. of elements\t";
cin>>n;
cout<<"\nEnter the sorted elments for optimal merge pattern";
for(i=0;i<n;i++)
{
cout<<"\t";
cin>>a[i];
}
i=0;k=0;
c[k]=a[i]+a[i+1];
i=2;
while(i<n)
{
k++;
if((c[k-1]+a[i])<=(a[i]+a[i+1]))
{
c[k]=c[k-1]+a[i];
}
else
{
c[k]=a[i]+a[i+1];
i=i+2;
while(i<n)
{ k++;
if((c[k-1]+a[i])<=(c[k-2]+a[i]))
{
c[k]=c[k-1]+a[i];
}
else
{
c[k]=c[k-2]+a[i];
}i++;
}
}i++;
}
k++;
c[k]=c[k-1]+c[k-2];
cout<<"\n\nThe optimal sum are as follows......\n\n";
for(k=0;k<n-1;k++)
{
cout<<c[k]<<"\t";
}
l=0;
for(k=0;k<n-1;k++)
{
l=l+c[k];
}
cout<<"\n\n The external path length is ......"<<l;
getch();
LAB EXERCISE 7

AIM

Write a program for KNAPSACK Problem

INTRODUCTION

The knapsack problem or rucksack problem is a problem in combinatorial optimization:


Given a set of items, each with a weight and a value, determine the number of each item to
include in a collection so that the total weight is less than a given limit and the total value is as
large as possible. It derives its name from the problem faced by someone who is constrained by a
fixed-size knapsack and must fill it with the most useful items.
The problem often arises in resource allocation with financial constraints. A similar problem also
appears in combinatory, complexity theory, cryptography and applied mathematics.
In the following, we have n kinds of items, 1 through n. Each kind of item i has a value vi and a
weight wi. We usually assume that all values and weights are nonnegative. The maximum weight
that we can carry in the bag is W.
The most common formulation of the problem is the 0-1 knapsack problem, which restricts the
number xi of copies of each kind of item to zero or one. Mathematically the 0-1-knapsack
problem can be formulated as:

● maximize

● subject to
The bounded knapsack problem restricts the number xi of copies of each kind of item to a
maximum integer value ci. Mathematically the bounded knapsack problem can be formulated as:

● maximize

● subject to
The unbounded knapsack problem places no upper bound on the number of copies of each
kind of item.
Of particular interest is the special case of the problem with these properties:

● it is a decision problem,

● it is a 0-1 problem,

● for each kind of item, the weight equals the value: wi = vi.
Notice that in this special case, the problem is equivalent to this: given a set of nonnegative
integers, does any subset of it add up to exactly W? Or, if negative weights are allowed and W is
chosen to be zero, the problem is: given a set of integers, does any subset add up to exactly 0?
This special case is called the subset sum problem. In the field of cryptography the term
knapsack problem is often used to refer specifically to the subset sum problem.
If multiple knapsacks are allowed, the problem is better thought of as the bin packing problem.

ALGORITHM

PROGRAM

#include<iostream.h>
#include<conio.h>
void swap(float x[],int j)
{
float temp=x[j];x[j]=x[j+1];x[j+1]=temp;
}
void main()
{
clrscr();
float w[5],p[5],x[5],m,u,d[5],optim=0;
int i,j;
cout<<"enter weight"<<endl;
for( i=0;i<5;i++)
{
cin>>w[i];
}
cout<<"Enter profit"<<endl;
for( i=0;i<5;i++)
{
cin>>p[i];
}
cout<<"enter max. capacity"<<endl;
cin>>m;
u=m;
for(i=0;i<5;i++)
{
x[i]=0.0;
}
for(i=0;i<5;i++)
{
d[i]=p[i]/w[i];
}
for( i=0;i<4;i++)
{
for( j=0;j<4;j++)
{
if(d[j]<d[j+1])
{
swap(d,j);
swap(p,j);
swap(w,j);
}
}
}
for(i=0;i<5;i++)
{
if(w[i]>u)
{
x[i]=u/w[i];
}
else
{ x[i]=1;
u=u-w[i];}
}

for(i=0;i<5;i++)
{
cout<<x[i]<<" ";
}
for(i=0;i<5;i++)
{
optim=optim+p[i]*x[i];
}
cout<<endl<<"Optimal solution="<<optim<<endl;
getch();
}

PROGRAM

SAMPLE OUTPUT

QUESTIONS
LAB EXERCISE 8

AIM

Implement Prim’s algorithm to find minimum cost spanning tree

INTRODUCTION

Prim's algorithm is an algorithm in graph theory that finds a minimum spanning tree for a
connected weighted graph. This means it finds a subset of the edges that forms a tree that
includes every vertex, where the total weight of all the edges in the tree is minimized. The
algorithm was discovered in 1930 by mathematician Vojtěch Jarník and later independently by
computer scientist Robert C. Prim in 1957 and rediscovered by Edsger Dijkstra in 1959.
Therefore it is sometimes called the DJP algorithm, the Jarník algorithm, or the Prim-Jarník
algorithm

ALGORITHM

Given a connected graph G=(V,E) and a weight d:E->R+, find a minimum spanning tree.
Prim's algorithm is known to be a good algorithm to find a minimum spanning tree.
1. Set i=0, S0= {u0=s}, L(u0)=0, and L(v)=infinity for v <> u0. If |V| = 1 then stop, otherwise
go to step 2.
2. For each v in V\Si, replace L(v) by min{L(v), dvui}. If L(v) is replaced, put a label (L(v),
ui) on v.
3. Find a vertex v which minimizes {L(v): v in V\Si}, say ui+1.
4. Let Si+1 = Si cup {ui+1}.
5. Replace i by i+1. If i=|V|-1 then stop, otherwise go to step 2

PSEUDO CODE

float Prim(int E[][SIZE], float cost[][SIZE], int n, int t[][2])


{
int near[SIZE], j, k, L;
let (k,L) be an edge of minimum cost in E;
float mincost = cost[k][L];
t[1][1] = k; t[1][2] = L;
for (int i=1; i<=n; i++) // Initialize near.
if (cost[i][L] < cost[i][k]) near[i] = L;
else near[i] = k;
near[k] = near[L] = 0;
for (i=2; i <= n-1; i++) { // Find n-2 additional
// edges for t.
let j be an index such that near[j]!=0 and
cost[j][near[j]] is minimum;
t[i][1] = j; t[i][2] = near[j];
mincost = mincost + cost[j][near[j]];
near[j]=0;
for (k=1; k<=n; k++) // Update near[].
if ((near[k]!=0) &&
(cost[k][near[k]]>cost[k][j]))
near[k] = j;
}
return(mincost);
}

PROGRAM

# include<iostream.h>
# include<conio.h>
int G[20][20];
void Prim(int nodes)
{
int select[20], i, j, k,INFINITY=30000;
int min_dist, v1, v2,total=0;
for (i=0; i<nodes ; i++) // Initialize the selected vertices list
select[i] = 0;

cout<<"\n\n The Minimal Spanning Tree Is :\n";


select[0] = 1;
for (k=1 ; k<=nodes-1 ; k++)
{
min_dist = INFINITY;
for (i=0; i<=nodes-1 ; i++) // Select an edge such that one vertex is
{ // selected and other is not and the edge
for (j=0; j<=nodes-1 ; j++) // has the least weight.
{
if(G[i][j] && ((select[i] && !select[j]) || (!select[i] &&
select[j])))
{
if (G[i][j] < min_dist)//obtained edge with minimum wt
{
min_dist = G[i][j];
v1 = i;
v2 = j; //picking up those vertices
}
}
}
}
cout<<"\n Edge ("<<v1<<" "<<v2<<")and weight ="<<min_dist<<endl;
select[v1] = select[v2] = 1;
total =total+min_dist;
}
cout<<"\n\n\t Total Path Length Is = "<<total<<endl;
}

void main()
{
int nodes;
int v1, v2, length, i, j, n;

clrscr();
cout<<"\n\t Prim'S Algorithm\n";
cout<<"\n Enter Number of Nodes in The Graph ";
cin>>nodes;
cout<<"\n Enter Number of Edges in The Graph ";
cin>>n;
for (i=0; i<nodes ; i++) // Initialize the graph
for (j=0 ; j<nodes ; j++)
G[i][j] = 0;
//entering weighted graph
cout<<"\n Enter edges and weights \n";
for (i=0; i<n; i++)
{
cout<<"\n Enter Edge by V1 and V2 :";
cin>>v1>>v2;
cout<<"\n Enter corresponding weight :";
cin>>length;
G[v1][v2] = G[v2][v1] = length;
}
getch();
cout<<"\n\t";
clrscr();
Prim(nodes);
getch();
}

SAMPLE OUTPUT

QUESTIONS

You might also like