You are on page 1of 49

VISHVESHWARYA GROUP OF INSTITUTIONS

Department of Computer Science & Engineering

Lab File: 2021-22

Design and Analysis of Algorithms Lab

(KCS-553)

Submitted To:- Submitted By:-

Mrs. Sunita Singh Student name:

CSE DEPTT. Roll no


List of Experiments Design and Analysis of Algorithm
Lab (KCS-553)

S.No. Name of Experiment


1 Program for Binary search

2 Program for Linear search


3 Program for insertion sort
4 Program for selection sort
5 Program for merge sort
6 Program for Quick sort
7 Program for Heap sort
8 Program for Knap -Sack problem using greedy approach
9 Program for Travelling salesman problem
10 Program for N-Queen problem using backtracking
11 Program for minimum spanning tree using kruskal’s algorithm
12 Program for Shell sort
13 Program for counting sort
14 Program for Bubble sort
Experiment -1

OBJECTIVE: - Program for Recursive Binary Search.

Brief Theory:-A binary search will start by examining the middle item. If that item is the one we
are searching for, we are done. If it is not the correct item, we can use the ordered nature of the
list to eliminate half of the remaining items. If the item we are searching for is greater than
the middle item, we know that the entire lower half of the list as well as the middle item can be
eliminated from further consideration. The item, if it is in the list, must be in the upper half.

We can then repeat the process with the upper half. Start at the middle item and compare
it against what we are looking for. Again, we either find it or split the list in half, therefore
eliminating another large part of our possible search space.

Procedure:-Given an array A of n elements with values or records A0 ... An−1 and target
value T, the following subroutine uses binary search to find the index of T in A.

1. Set L to 0 and R to n − 1.
2. If L > R, the search terminates as unsuccessful. Set m (the position of the middle element) to the
floor of (L + R) / 2.
3. If Am < T, set L to m + 1 and go to step 2.
4. If Am > T, set R to m − 1 and go to step 2.
5. If Am = T, the search is done; return m.

Program:-

#include<stdio.h>
int main(){

int a[10],i,n,m,c,l,u;

printf("Enter the size of an array: ");


scanf("%d",&n);

printf("Enter the elements of the array: " );


for(i=0;i<n;i++){
scanf("%d",&a[i]);
}

printf("Enter the number to be search: ");


scanf("%d",&m);
l=0,u=n-1;
c=binary(a,n,m,l,u);
if(c==0)
printf("Number is not found.");
else
printf("Number is found.");

return 0;
}

int binary(int a[],int n,int m,int l,int u){

int mid,c=0;

if(l<=u){ mid=(l+u)/2;
if(m==a[mid]){
c=1;
}
else if(m<a[mid]){
return binary(a,n,m,l,mid-1);
}
else
return binary(a,n,m,mid+1,u);
}
else
return c;
}

Result:-

Enter the size of an array: 5


Enter the elements of the array: 8 9 10 11 12
Enter the number to be search: 8
Number is found.
Viva-voce Questions

1. What do you mean by Amortized Analysis?


Amortized analysis finds the average running time per operation over a worst case sequence of
operations. Amortized analysis differs from average-case performance in that probability is not
involved; amortized analysis guarantees the time per operation over worst-case performance.
2. What is an Algorithm?
An algorithm is a sequence of unambiguous instructions for solving a problem, i.e., for obtaining
a required output for any legitimate input in a finite amount of time.
3. What is recursive call?
Recursive algorithm makes more than a single call to itself is known as recursive call.
An
algorithm that calls itself is direct recursive. An algorithm ”A” is said to be indirect recursive if it
calls another algorithm which in turn calls “A”.
4. What is the binary search?
If ‘q’ is always chosen such that ‘aq’ is the middle element (that is, q=[(n+1)/2), then the
resulting search algorithm is known as binary search.
5. Give computing time for Binary search?
In conclusion we are now able completely describe the computing time of binary search by
giving formulas that describe the best, average and worst cases.
Successful searches

Unsuccessful searches
Θ(1) Θ (logn) Θ (Logn)
best average worst

Θ (logn)
Experiment-2

Objective: - Program for Recursive Linear Search.

Brief Theory:- Linear search or sequential search is a method for finding a target value
within a list. It sequentially checks each element of the list for the target value until a
match is found or until all the elements have been searched. Linear search runs in at worst linear
time and makes at most n comparisons, where n is the length of the list
Procedure:-

1. LinearSearch(value, list)
2. if the list is empty, return item_not_found;
3. else
4. if the first item of the list has the desired value, return its location;
5. else return LinearSearch(value, remainder of the list)
Program:-
#include<stdio.h>
int main(){
int a[10],i,n,m,c=0;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i=0;i<=n-1;i++){
scanf("%d",&a[i]);
}
printf("Enter the number to be search: ");
scanf("%d",&m);
for(i=0;i<=n-1;i++){
if(a[i]==m){
c=1;
break;
}
}
if(c==0)
printf("The number is not in the list");
else
printf("The number is found");

return 0;

Results:
Enter the size of an array: 5
Enter the elements of the array: 4 6 8 0 3
Enter the number to be search: 0
The number is found

Viva-voce Questions

1. What do you mean by “Searching” problem?


The searching problem deals with finding a given value, called a search key, in a given set.
2. What do you mean by ²Worst case-Efficiency” of an algorithm?
The ²Worst case-Efficiency” of an algorithm is its efficiency for the worst-case input of size n,
which is an input (or inputs) of size n for which the algorithm runs the longest among all possible
inputs of that size.
3. What is the linear search?
It sequentially checks each element of the list for the target value until a match is found or until
all the elements have been searched.
4. What is the complexity of linear search in worst case?
O(n)
5. What is the complexity of linear search in best case?
O(1)
Experiment -3

Objective: - Program for Insertion Sort.

Brief Theory:- Insertion sort is a simple sorting algorithm that builds the final sorted array (or
list) one item at a time. It is much less efficient on large lists than more advanced
algorithms such as quicksort, heapsort, or merge sort. However, insertion sort provides several
advantages:

Efficient for (quite) small data sets, much like other quadratic sorting algorithms
More efficient in practice than most other simple quadratic (i.e., O(n2)) algorithms such
as selection sort or bubble sort
Adaptive, i.e., efficient for data sets that are already substantially sorted: the time complexity is
O(nk) when each element in the input is no more than k places away from its sorted position
Stable; i.e., does not change the relative order of elements with equal keys

Procedure:-

1. for i ← 1 to length(A)-1
2. j ← i
3. while j > 0 and A[j-1] > A[j]
4. swap A[j] and A[j-1] 5.j
←j–1
6. end while
7. end for

Program:-
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i,t,a[100],d,n;
printf("Enter The No. Of Elements\n");
scanf("%d",&n);
printf("Enter %d Integers\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}

for(i=1;i<=n-1;i++)
{
d=i;
while(d>0&&a[d]<a[d-1])
{ t=a[d];
a[d]=a[d-1];
a[d-1]=t;
d--;
}
}
printf("Sorted List in Ascending Order is:\n");
for(i=0;i<=n-1;i++)
{
printf("%d\t",a[i]);
}
getch();
}

Results:
Enter the No. of Elements: 5
Enter 5 integers: 11, 1, 14, 9, 4
Sorted List in Ascending Order Using Insertion Sort is: 1, 4, 9, 11, 14

Viva-voce Questions

1. What is Insertion sort?


Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a
time.
2. Analyze insertion sort?
O(n2)
3. Is insertion sort stable in nature?
Yes
4. What are the advantages of Insertion sort?
Efficient
Adaptive
Stable
Experiment-4

Objective: - Program for Merge Sort.

Brief Theory:- Merge sort is based on the divide-and-conquer paradigm. Its worst- case
running time has a lower order of growth than insertion sort. Since we are dealing with sub
problems, we state each sub problem as sorting a sub array A[p .. r]. Initially, p = 1 and r = n, but
these values change as we recurs through sub problems. To sort A[p .. r]:

1. Divide Step

If a given array A has zero or one element, simply return; it is already sorted. Otherwise, split A[p
.. r] into two subarrays A[p .. q] and A[q + 1 .. r], each containing about half of the elements of A[p
.. r]. That is, q is the halfway point of A[p .. r].

2. Conquer Step

Conquer by recursively sorting the two subarrays A[p .. q] and A[q + 1 .. r].

3. Combine Step

Combine the elements back in A[p .. r] by merging the two sorted subarrays A[p .. q] and A[q + 1
.. r] into a sorted sequence. To accomplish this step, we will define a procedure MERGE (A, p, q,
r).

Procedure:-

To sort the entire sequence A[1 .. n], make the initial call to the procedure MERGE-SORT (A, 1,
n).

MERGE-SORT (A, p, r)

1. IF p < r // Check for base case


2. THEN q = FLOOR[(p + r)/2] // Divide step
3. MERGE (A, p, q) // Conquer step.
4. MERGE (A, q + 1, r) // Conquer step.
5. MERGE (A, p, q, r) // Conquer step.
Program:-

#include <stdio.h>
#include<conio.h>
void mergesort(int arr[], int l, int h);
void main(void)
{
int array[100],n,i = 0;
clrscr();
printf("\t\t\tMerge Sort\n\n\n\n");
printf("Enter the number of elements to be sorted: ");
scanf("%d",&n);
printf("\nEnter the elements to be sorted: \n");
for(i = 0 ; i < n ; i++ )
{
printf("\tArray[%d] = ",i);
scanf("%d",&array[i]);
}
printf("\nBefore Mergesort:");
for(i = 0; i < n; i++)
{
printf("%4d", array[i]);
} printf("\n");
mergesort(array, 0, n - 1);
printf("\nAfter Mergesort:");
for(i = 0; i < n; i++)
{
printf("%4d", array[i]);
}
printf("\n");
getch();
}
void mergesort(int arr[], int l, int h)
{
int i = 0;
int length = h - l + 1;
int pivot = 0;
int merge1 = 0;
int merge2 = 0;
int temp[100];
if(l == h)
return;
pivot = (l + h) / 2;

mergesort(arr, l, pivot);
mergesort(arr, pivot + 1, h);
for(i = 0; i < length; i++)
{
temp[i] = arr[l + i];
}
merge1 = 0;
merge2 = pivot - l + 1;
for(i = 0; i < length; i++)
{
if(merge2 <= h - l)
{
if(merge1 <= pivot - l)
{
if(temp[merge1] > temp[merge2])
{
arr[i + l] = temp[merge2++];
}
else
{
arr[i + l] = temp[merge1++];
}
}
else
{
arr[i + l] = temp[merge2++];
}
}
else
{
arr[i + l] = temp[merge1++];
}
}
}

Results:
Enter the No. of Elements to be sorted: 7
Enter the elements to be sorted: 11, 1, 14, 4, 18, 16, 9.
Sorted List in Ascending Order Using Merge Sort is: 1, 4, 9, 11, 14, 16, 18.

Viva –Voce Questions

1. What is Merge sort?


Merge sort is divide and conquer strategy that works by dividing an input array in to two halves,
sorting them recursively and then merging the two sorted halves to get the original array sorted
2. Is insertion sort better than the merge sort?
Insertion sort works exceedingly fast on arrays of less then 16 elements, though for large ‘n’ its
computing time is O(n2).
3. Write the Analysis for the Quick sort.
O(n logn)
4. Is merge sort is based on divide and conquer strategy?
Yes
5. Define the divide an conquer method.
Given a function to compute on ‘n’ inputs the divide-and-comquer strategy suggests splitting the
inputs in to’k’ distinct susbsets, 1<k <n, yielding ‘k’ subproblems. The subproblems must
be solved, and then a method must be found to combine subsolutions into a solution of the whole.
If the subproblems are still relatively large, then the divide-and conquer strategy can possibly be
reapplied.
Experiment -5

Objective: - Program for Selection Sort.

Brief Theory:- Selection sort is a sorting algorithm, specifically an in-place comparison


sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse
than the similar insertion sort. Selection sort is noted for its simplicity, and it has performance
advantages over more complicated algorithms in certain situations, particularly where auxiliary
memory is limited.

The algorithm divides the input list into two parts: the sublist of items already sorted, which is built
up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that
occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire
input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order)
element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element
(putting it in sorted order), and moving the sublist boundaries one element to the right.

Procedure:-

SELECTION_SORT (A)

for i ← 1 to n-1 do
min j ← i;
min x ← A[i]
for j ← i + 1 to n do
If A[j] < min x then
min j ← j
min x ← A[j]
A[min j] ← A [i]
A[i] ← min x

Program:-

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i,position,swap,a[100],d,n;
printf("Enter The No. Of Elements\n");

scanf("%d",&n);
printf("Enter %d Integers\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<(n-1);i++)
{ position=i;
for(d=c+1;d<n;d++)
{
if(array[position]>array[d])
position=d;
}
if(position!=i)
{ swap=a[i];
a[i]=a[position];
a[position]=swap;
}
}
printf("Sorted List in Ascending Order is:\n");
for(i=0;i<=n;i++)
{
printf("%d\t",a[i]);
}
getch();
}

Results:
Enter the No. of Elements to be sorted: 5
Enter 5 integers: 70, 12, 50, 20, 10
Sorted List in Ascending Order Using Selection Sort is: 10, 12, 20, 50, 70

1. What is Selection sort?


Viva –Voce Questions
Selection sort divides the input list into two parts: the sublist of items already sorted, which is
built up from left to right at the front (left) of the list, and the sublist of items remaining to be
sorted that occupy the rest of the list.
2. What is the time complexity of selection sort?
O(n2)
3. What is the substitution method?
One of the methods for solving any such recurrence relation is called the substitution method.
4. Define input size.
The input size of any instance of a problem is defined to be the number of words (or the number
of elements) needed to describe that instance.
Experiment-6

Objective: - Program for Quick Sort.

Brief Theory:- Quicksort is a divide and conquer algorithm. Quicksort first divides a large array
into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively
sort the sub-arrays.

The steps are:

1. Pick an element, called a pivot, from the array.


2. Partitioning: reorder the array so that all elements with values less than the pivot come before the
pivot, while all elements with values greater than the pivot come after it (equal values can go either
way). After this partitioning, the pivot is in its final position. This is called the partition operation.
3. Recursively apply the above steps to the sub-array of elements with smaller values and
separately to the sub-array of elements with greater values.

Procedure:-

quicksort(A, lo, hi)


5. if lo < hi then
6. p := partition(A, lo, hi)
7. quicksort(A, lo, p – 1)
8. quicksort(A, p + 1, hi)
partition(A, lo, hi)
1. pivot := A[hi]
2. i := lo // place for swapping
3. for j := lo to hi – 1 do
4. if A[j] ≤ pivot then
5. swap A[i] with A[j] 6. i
:= i + 1
7. swap A[i] with A[hi]
8. return i
Program:-

#include<stdio.h

#include<conio.h>
void quicksort(int [10],int,int);
void main()
{
clrscr();
int a[20],n,i;
printf("Enter size of the array:\n");
scanf("%d",&n);
printf("Enter %d elements:\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
quicksort(a,0,n-1);
printf("Sorted elements:\n ");
for(i=0;i<n;i++)
{
printf("\t%d",a[i]);
}
getch();
}
void quicksort(int a[10],int first,int last)
{
int pivot,j,temp,i;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(a[i]<=a[pivot]&&i<last)
i++;
while(a[j]>a[pivot])
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}

temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
quicksort(a,first,j
-1);
quicksort(a,j+1,l
ast);
}
}

Results:
Enter the No. of Elements to be sorted: 5
Enter 5 integers: 70, 12, 50, 20, 10
Sorted List in Ascending Order Using Quick Sort is: 10, 12, 20, 50, 70

Viva-voce Questions

1. What is the Quick sort?


Quicksort is divide and conquer strategy that works by partitioning it’s input elements
according
to their value relative to some preselected element(pivot). it uses recursion and the method is
also called partition –exchange sort.
2. Write the Analysis for the Quick sort.
O(nlogn) in average and best cases
O(n2) in worst case
3. What do you understand by divide and conquer approach?
Given a function to compute on ‘n’ inputs the divide-and-comquer strategy suggests splitting
the
inputs in to’k’ distinct susbsets, 1<k <n, yielding ‘k’ subproblems. The subproblems
must be solved, and then a method must be found to combine subsolutions into a solution of
the whole. If the subproblems are still relatively large, then the divide-and conquer strategy can
possibly be reapplied.
4. What are the different criteria used to improve the effectiveness of
algorithm? The effectiveness of algorithm is improved, when the design,
satisfies the following constraints to be minimum.
Time efficiency - how fast an algorithm in question
runs. Space efficiency – an extra space the algorithm
requires
The algorithm has to provide result for all valid
inputs.
Experiment -7

Objective: Program for heap sort


Brief Theory:- Heapsort is a comparison-based sorting algorithm. Heapsort can be
thought of as an improved selection sort: like that algorithm, it divides its input into a sorted and
an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element
and moving that to the sorted region. Heap Sort is one of the best sorting methods being in-place
and with no quadratic worst-case scenarios. Heap sort algorithm is divided into two basic parts:

Creating a Heap of the unsorted list.


Then a sorted array is created by repeatedly removing the largest/smallest element from the
heap, and inserting it into the array. The heap is reconstructed after each removal.

Procedure:-

The steps are:

1. Call the buildMaxHeap() function on the list. Also referred to as heapify(), this builds a heap
from a list in O(n) operations.
2. Swap the first element of the list with the final element. Decrease the considered range of the
list by one.
3. Call the Adjust() function on the list to sift the new first element to its appropriate index in
the heap.
4. Go to step (2) unless the considered range of the list is one element.

Program:-

#include<stdio.h>
#include<conio.h>
void heapsort(int[], int);
void heapify(int[], int);
void adjust(int[], int);
int main()
{
int array[50],n,i;
clrscr();
printf("Enter the no. of elements to be sorted:\n ");
scanf("%d",&n);
printf("Enter %d elements: \n",n);
for(i=0 ; i<n ; i++)
{
scanf("%d",&array[i]);

heapsort(array,n);
printf("Sorted list in ascending order using heap sort is:\n");
for(i = 0; i < n; i++)
{
printf("%d\t", array[i]);
}
printf("\n");
getch();
return 0;
}
void heapsort(int array[], int n)
{
int i,t;
heapify(array,n);
for(i=n-1 ; i>0 ; i--)
{
t = array[0];
array[0] = array[i];
array[i] = t;
adjust(array,i);
}
}
void heapify(int array[], int n)
{
int item,i,j,k;
for(k=1 ; k<n ; k++)
{
item = array[k];
i = k;
j = (i-1)/2;
while( (i>0) && (item>array[j]) )
{
array[i] = array[j];
i = j;
j = (i-1)/2;
}
array[i] = item;
}
}
void adjust(int array[], int n)
{
int item,i,j;

j = 0;
item = array[j];
i = 2*j+1;
while(i<=n-1)
{
if(i+1 <= n-1)
if(array[i] < array[i+1])
i++;
if(item < array[i])
{
array[j] = array[i];
j = i;
i = 2*j+1;
} else
break;
}
array[j] = item;
}

Results:
Enter the No. of Elements to be sorted: 5
Enter 5 integers: 70, 12, 50, 20, 15
Sorted List in Ascending Order Using Heap Sort is: 12, 15, 20, 50, 70

Viva-voce Questions
1. What is the average case complexity for heap sort algorithm?
O(n logn)

2. What is the best case complexity for heap sort algorithm?


O(n logn)

3. What is the condition applicable for max-heap?


A[Parent(i)]>=A[i]

4. What is heap sort?


Heap sort is one of the best methods being in-place and with no quadratic worst case
scenarios.It is a comparision based sorting algorithm, ans is part of the selection sort family.
The operations performed by heap sort algorithm are:
BUILD-MAX-HEAP:To build a max heap with the given [1,n] elements.

MAX-HEAPIFY:Which modifies a heap with [1,n-1] elements so that it satifies the


properties of a heap.

5. What is the condition applicable for min-heap?


A[Parent(i)]<=A[i]
Experiment-8

Objective: - Program to perform knapsack problem using Greedy Approach.

Brief Theory:- 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 or equal to 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 valuable items.

Procedure:-

1. // Input:
2. // Values (stored in array v)
3. // Weights (stored in array w)
4. // Number of distinct items (n)
5. // Knapsack capacity (W)
6. for j from 0 to W do:
7. m[0, j] := 0
8. for i from 1 to n do:
9. for j from 0 to W do:
10. if w[i-1] > j then:
11. m[i, j] := m[i-1, j]
12. else:
13. m[i, j] := max(m[i-1, j], m[i-1, j-w[i-1]] + v[i-1])

Program:-

#include<stdio.h>
#include<conio.h>
void knapsack(int n, float weight[], float profit[], float capacity)
{
float x[20], tp = 0;
int i, j, u;
u = capacity;
for (i = 0; i < n; i++)
x[i] = 0.0;
for (i = 0; i < n; i++)
{
if (weight[i] > u)

break;
else
{
x[i] = 1.0;
tp = tp + profit[i];
u = u - weight[i];
}
}
if (i < n)
x[i] = u / weight[i];
tp = tp + (x[i] * profit[i]);
printf("\nThe result vector is:- ");
for (i = 0; i < n; i++)
printf("%f\t", x[i]);
printf("\nMaximum profit is:- %f", tp);
}
void main()
{
clrscr();
float weight[20], profit[20], capacity;
int num, i, j;
float ratio[20], temp;
printf("\nEnter the no. of objects:- ");
scanf("%d", &num);
printf("\nEnter the weights and profits of each object:- ");
for (i = 0; i < num; i++)
{
scanf("%f %f", &weight[i], &profit[i]);
}
printf("\nEnter the capacity of knapsack:- ");
scanf("%f", &capacity);
for (i = 0; i < num; i++)
{
ratio[i] = profit[i] / weight[i];
}
for (i = 0; i < num; i++)
{
for (j = i + 1; j < num; j++)
{
if (ratio[i] < ratio[j])
{
temp = ratio[j];

ratio[j] = ratio[i];
ratio[i] = temp;
temp=weight[j];
weight[j] = weight[i];
weight[i] = temp;
temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
}
}
knapsack(num, weight, profit, capacity);
getch();
}

Results:

Enter the no. of objects: - 7

Enter the weights and profits of each object: - 2, 10

3, 5
5, 15
7, 7
1, 6
4, 18
1, 3
Enter the capacity of knapsack: - 15
The result vector is: - 1.000000 1.000000 1.000000 1.000000 1.000000 0.666667 0.000000
Maximum profit is: - 55.333332
Viva –Voce Questions

1. What do you understand by greedy approach?


A greedy algorithm is an algorithm that follows the problem solving heuristic of making
the locally optimal choice at each stage with the hope of finding a global optimum.
2. Enlist some of the algorithm motivated by greedy approach.
Knapsack problem
Job scheduling problem
MST algorithms
Huffman Coding
3. What do you understand by knapsack problem?
Knapsack 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 or equal to a given limit and the total value is as large as
possible.
4. Enlist the name of different variants of Knapsack problem.
0/1 knapsack problem
Fractional knapsack problem
5. Define fractional knapsack?
Fractional knapsack problem is an algorithmic problem in combinatorial optimization in
which the goal is to fill a container (the "knapsack") with fractional amounts of different
materials chosen to maximize the value of the selected materials
6. What are the steps required to develop a greedy algorithm?
* Determine the optimal substructure of the problem.
* Develop a recursive solution.
* Prove that at any stage of recursion one of the optimal choices is greedy choice.
Thus it is always safe to make greedy choice.
* Show that all but one of the sub problems induced by having made the greedy choice are
empty.
* Develop a recursive algorithm and convert into iterative algorithm.
Experiment-9

Objective: - Program to find the minimum spanning tree using Kruskal’s algorithm.

Brief Theory:- Kruskal's algorithm is a minimum-spanning-tree algorithm which finds an


edge of the least possible weight that connects any two trees in the forest. It is a greedy algorithm
in graph theory as it finds a minimum spanning tree for a connected weighted graph adding
increasing cost arcs at each step. 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. If the graph
is not connected, then it finds a minimum spanning forest (a minimum spanning tree for each
connected component).

Procedure:-

KRUSKAL(G):
1A=∅
foreach v ∈ G.V:
MAKE-SET(v)
foreach (u, v) in G.E ordered by weight(u, v), increasing:
if FIND-SET(u) ≠ FIND-SET(v):
6 A = A ∪ {(u, v)}
7 UNION(u, v)
8 return A

Program:-

#include<stdio.h>
#include<conio.h>
#define INF 0
char vertex[10];
int wght[10][10];
int span_wght[10][10];
int source;
struct Sort
{
int v1,v2;
int weight;
}que[20];
int n,ed,f,r;
int cycle(int s,int d)
{
int j,k;
if(source==d)

return 1; for(j=0;j<n;j++)
if(span_wght[d][j]!=INF && s!=j)
{
if(cycle(d,j))
return 1;
}
return 0;
}
void build_tree()
{
int i,j,w,k,count=0;
for(count=0;count<n;f++)
{ i=que[f].v1;
j=que[f].v2;
w=que[f].weight;
span_wght[i][j]=span_wght[j][i]=w;
source=i;
k=cycle(i,j);
if(k)
span_wght[i][j]=span_wght[j][i]=INF;
else
count++;
}
}
void swap(int *i,int *j)
{
int t;
t=*i;
*i=*j;
*j=t;
}
void main()
{
int i,j,k=0,temp;
int sum=0;
clrscr();
printf("\n\tEnter the No. of Nodes : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{

printf("\n\tEnter %d value : ",i+1);


fflush(stdin);
scanf("%c",&vertex[i]);
for(j=0;j<n;j++)
{ wght[i][j]=INF;
span_wght[i][j]=INF;
}
}
printf("\n\nGetting Weight\n");
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
printf("\nEnter 0 if path Doesn't exist between %c to %c : ",vertex[i],vertex[j]);
scanf("%d",&ed);
if(ed>=1)
{
wght[i][j]=wght[j][i]=ed;
que[r].v1=i;
que[r].v2=j;
que[r].weight=wght[i][j];
if(r)
{ for(k=0;k<r;k++)
if(que[k].weight>que[r].weight)
{
swap(&que[k].weight,&que[r].weight);
swap(&que[k].v1,&que[r].v1);
swap(&que[k].v2,&que[r].v2);
}
}
r++;
}
}
clrscr();
printf("\n\tORIGINAL GRAPH WEIGHT MATRIX\n\n");
printf("\n\tweight matrix\n\n\t");
for(i=0;i<n;i++,printf("\n\t"))
for(j=0;j<n;j++,printf("\t"))
printf("%d",wght[i][j]);
build_tree();
printf("\n\n\t\tMINIMUM SPANNING TREE\n\n");

printf("\n\t\tLIST OF EDGES\n\n");
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(span_wght[i][j]!=INF)
{
printf("\n\t\t%c ------- %c = %d ",vertex[i],vertex[j],span_wght[i][j]);
sum+=span_wght[i][j];
}
printf("\n\n\t\tTotal Weight : %d ",sum);
getch();
}

Results:
Original Graph Weight Matrix
Weight Matrix
0 4 8 6 7
4 0 2 9 0
8 2 0 8 5
6 9 8 0 3
7 0 5 3 0

Minimum Spanning Tree


List of edges
1 ------ 2 = 4
2 ------ 3 = 2
3 ------ 5 = 5
4 ------ 5 = 5

Total weight = 14

Viva-voce Questions

1. What is graph?
A graph is a pictorial representation of a set of objects where some pairs of objects are
connected by links. The interconnected objects are represented by points termed as vertices,
and the links that connect the vertices are called edges.

2. What is spanning tree?


A spanning tree is a subset of Graph G, which has all the vertices covered with minimum
possible number of edges. A spanning tree does not have cycles and it cannot be
disconnected.

3. How many spanning trees can a graph has?


It depends on how connected the graph is. A complete undirected graph can have maximum
nn-1 number of spanning trees, where n is number of nodes.

4. What is a minimum spanning tree (MST) ?


In a weighted graph, a minimum spanning tree is a spanning tree that has minimum weight
that all other spanning trees of the same graph.

5. How Kruskal's algorithm works?


This algorithm treats the graph as a forest and every node it as an individual tree. A tree
connects to another only and only if it has least cost among all available options and does not
violate MST properties.
Experiment No:10

Objective: - Program to perform Travelling Salesman Problem.

Brief Theory:-The Travelling Salesman Problem describes a salesman who must travel between
N cities. The order in which he does so is something he does not care about, as long as he visits
each one during his trip, and finishes where he was at first. Each city is connected to other close by
cities, or nodes, by airplanes, or by road or railway. Each of those links between the cities has one
or more weights (or the cost) attached. The cost describes how "difficult" it is to traverse this edge
on the graph, and may be given, for example, by the cost of an airplane ticket or train
ticket, or perhaps by the length of the edge, or time required to complete the traversal. The
salesman wants to keep both the travel costs, as well as the distance he travels as low as possible.

Procedure:-

1. stand on an arbitrary vertex as current vertex.


2. find out the lightest edge connecting current vertex and an unvisited vertex V.
3. set current vertex to V.
4. mark V as visited.
5. if all the vertices in domain are visited, then terminate.
6. Go to step 2.

Program:-

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int a[10][10],visited[10],n,cost=0;
void get()
{
int i,j;
printf("\n\nEnter Number of Cities: ");
scanf("%d",&n);
printf("\nEnter Cost Matrix: \n");
for( i=0;i<n;i++)
{
printf("\n Enter Elements of Row # : %d\n",i+1);
for( j=0;j<n;j++)

scanf("%d",&a[i][j]);
visited[i]=0;
}
printf("\n\nThe Cost Matrix is:\n");
for( i=0;i<n;i++)
{ printf("\n\n");
for(j=0;j<n;j++)
printf("\t%d",a[i][j]);
}
}
void mincost(int city)
{
int i,ncity,least(int city);
visited[city]=1;
printf("%d ===> ",city+1);
ncity=least(city);
if(ncity==999)
{ ncity=0;
printf("%d",ncity+1);
cost+=a[city][ncity];
return;
}
mincost(ncity);
}
int least(int c)
{
int i,nc=999;
int min=999,kmin;
for(i=0;i<n;i++)
{
if((a[c][i]!=0)&&(visited[i]==0))
if(a[c][i]<min)
{
min=a[i][0]+a[c][i];
kmin=a[c][i];
nc=i;
}
}
if(min!=999)
cost+=kmin;

return nc;
}
void put()
{
printf("\n\nMinimum cost:");
printf("%d",cost);
}
void main()
{
clrscr();
get();
printf("\n\nThe Path is:\n\n");
mincost(0);
put();
getch();
}

Results:

The Cost Matrix is:


14 15 18 34 98 12
45 67 81 34 12 8
23 86 15 3 57 34
47 92 31 7 68 39
95 85 10 55 72 43
63 86 93 56 13 49

The Path is:


1653421
Minimum cost: 175
Viva-voce Questions

1. What is travelling salesman problem?

Travelling Salesman Problem describes a salesman who must travel between N cities. The order
in which he does so is something he does not care about, as long as he visits each one during
his trip, and finishes where he was at first. Each city is connected to other close by

cities, or nodes, by airplanes, or by road or railway. Each of those links between the cities has
one or more weights (or the cost) attached. The cost describes how "difficult" it is to traverse
this edge on the graph, and may be given, for example, by the cost of an airplane ticket or train
ticket, or perhaps by the length of the edge, or time required to complete the traversal. The
salesman wants to keep both the travel costs, as well as the distance he travels as low as
possible.

2. What is the time complexity of TSP?


O (n.2n)

3. Let a complete graph G has n vertices and e edges. What will be the value of e in terms
of vertices n?
e = n (n-1)/2

4. Define forest.
Collection of sub trees that are obtained when root node is eliminated is known as forest

5. Write some applications of traveling salesperson problem.


Routing a postal van to pick up mail from boxes located at n different sites.
Using a robot arm to tighten the nuts on some piece of machinery on an assembly line.
Production environment in which several commodities are manufactured on the same set
of machines.
Experiment No.:11

Objective: - Program to implement N Queen Problem using Backtracking.

Brief Theory:-In this problem or puzzle, N queens will be given and the challenge is to place all
of them in N x N chessboard so that no two queens are in attacking position. What that means is
we need to find the configuration of N queens where any of the two queens do not share a row,
column and diagonal paths. One of the better and elegant solutions to this puzzle is
‘backtracking algorithm’.

Procedure:-

1. Place the queens column wise, start from the left most column
2. If all queens are placed.
1. return true and print the solution matrix.
3. Else
1. Try all the rows in the current column.
2. Check if queen can be placed here safely if yes mark the current cell in solution
matrix as 1 and try to solve the rest of the problem recursively.
3. If placing the queen in above step leads to the solution return true.
4. If placing the queen in above step does not lead to the solution , BACKTRACK,
mark the current cell in solution matrix as 0 and return false.
4. If all the rows are tried and nothing worked, return false and print NO SOLUTION.

Program:-

#include<stdio.h>
#include<conio.h>
#include<math.h>
char a[10][10];
int n;
void printmatrix()
{
int i, j;
printf("\n");
for (i = 0; i < n; i++)
{

for (j = 0; j < n; j++)


printf("%c\t", a[i][j]);
printf("\n\n");
}
}
int getmarkedcol(int row)
{
int i;
for (i = 0; i < n; i++)
if (a[row][i] == 'Q')
{
return (i);
break;
}
}
int feasible(int row, int col)
{
int i, tcol;
for (i = 0; i < n; i++)
{
tcol = getmarkedcol(i);
if (col == tcol || abs(row - i) == abs(col - tcol))
return 0;
}
return 1;
}
void nqueen(int row)
{
int i, j;
if (row < n)
{
for (i = 0; i < n; i++)
{
if (feasible(row, i))
{
a[row][i] = 'Q';
nqueen(row + 1);
a[row][i] = '.';
}
}
}
else

{
printf("\nThe solution is:- ");
printmatrix();
}
}
void main()
{
clrscr();
int i, j;
printf("\nEnter the no. of queens:- ");
scanf("%d", &n);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
a[i][j] = '.';
nqueen(0);
getch();
}

Results:
Enter the no. of queens: - 4
The solution is: -
. Q . .
. . . Q
Q . . .
. . Q .
The solution is: -
. . Q .
Q . . .
. . . Q
. Q . .
Viva-voce Questions

1. What do you understand by backtracking?


Backtracking is a general algorithm for finding all (or some) solutions to some computational
problems, notably constraint satisfaction problems, that incrementally builds candidates to
the solutions, and abandons each partial candidate c ("backtracks") as soon as it determines
that c cannot possibly be completed to a valid solution.

2. Explain n-Queens problem

The problem is to place n queens on an n by n chessboard so that no two queens attack each
other by being in the same row or same column or on the same diagonal.

3. State 8 – Queens problem.


The problem is to place eight queens on a 8 x 8 chessboard so that no two queen “attack” that
is, so that no two of them are on the same row, column or on the diagonal.
Experiment -12

Objective : Program for shell sort

Shell sort, also known as Shell sort or Shell’s method, is an in-place comparison sort. It can either
be seen as a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion
sort). The method starts by sorting elements far apart from each other and progressively reducing the
gap between them. Starting with far apart elements can move some out-of-place elements into
position faster than a simple nearest neighbor exchange. Here is the source code of the C program to
sort integers using Shell Sort technique. The C program is successfully compiled and run on a Linux
system. The program output is also shown below.

1. * C Program to sort an array using Shell Sort technique

2. #include <stdio.h>
3. void shellsort(int arr[], int num) 4.
{
5. int i, j, k, tmp;
6. for (i = num / 2; i > 0; i = i / 2)
7. {
8. for (j = i; j < num; j++)
9. {
10. for(k = j - i; k >= 0; k = k - i)
11. {
12. if (arr[k+i] >= arr[k])
13. break;
14. else
15. {
16. tmp = arr[k];
17. arr[k] = arr[k+i];
18. arr[k+i] = tmp;
19. }
20. }
21. }
22. }
23. }
24. int main()
25. {
26. int arr[30];
27. int k, num;
28. printf("Enter total no. of elements : ");
29. scanf("%d", &num);
30. printf("\nEnter %d numbers: ", num); 31.
32. for (k = 0 ; k < num; k++)
33. {
34. scanf("%d", &arr[k]);
35. }
36. shellsort(arr, num);
37. printf("\n Sorted array is: ");
38. for (k = 0; k < num; k++)
39. printf("%d ", arr[k]);
40. return 0;
41. }
Input/output

Enter total no. of elements : 10


Enter numbers : 36 432 43 44 57 63 94 3 5 6
Sorted array is : 3 5 6 36 43 44 57 63 94 432

Viva-voce Questions
Q.1 What is shell sort

Shell sort, also known as Shell sort or Shell’s method, is an in-place comparison sort. It can either
be seen as a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion
sort).

Q.2 what is the complexity of shell sort

Worst case time complexity is O(n2) and best-case complexity is O(n log(n)).
Experiment-13

Objective: Program for bubble sort

Bubble sort is also known as sinking sort. This algorithm compares each pair of adjacent items and
swaps them if they are in the wrong order, and this same process goes on until no swaps are
needed. In the following program we are implementing bubble sort in C language. In this program
user would be asked to enter the number of elements along with the element values and then the
program would sort them in ascending order by using bubble sorting algorithm logic.

Implementing bubble sort algorithm in a C program


/* Implementing Bubble sort in a C Program

#include<stdio.h>

int main(){

int count, temp, i, j, number[30];

printf("How many numbers are u going to enter?: ");


scanf("%d",&count);

printf("Enter %d numbers: ",count);

for(i=0;i<count;i++)
scanf("%d",&number[i]);

/* This is the main logic of bubble sort algorithm


*/
for(i=count-2;i>=0;i--){
for(j=0;j<=i;j++){
if(number[j]>number[j+1]){
temp=number[j];
number[j]=number[j+1];
number[j+1]=temp;
}
}
}
printf("Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);

return 0;
}

Output:

Viva-voce Questions

Q-1 What is bubble sort

Bubble sort is also known as sinking sort. This algorithm compares each pair of adjacent items and
swaps them if they are in the wrong order, and this same process goes on until no swaps are
needed. In the following program we are implementing bubble sort in C language
Experiment -14

Objective: Program for counting sort

Counting sort algorithm is a sorting algorithm which do not involve comparison between elements
of an array1.

First of all I am reading n elements in array a[]. While reading the array elements I have also
calculated the maximum element.

2. Now the actual sorting is done in counting_sort() function. Here I am counting the occurrence of
each element in the array a[] and then storing it at the index equal to the value of that element. For
example occurrence of element 5 will be stored at index 5, occurrence of element 9 will be stored
at index 9 and so on.

3. As the value at each index in count[] array is the occurrence of that index or element, so the
elements are printed in ascending order by printing each index number of times equal to its
corresponding value.

1 #include<stdio.h>
2
3 void counting_sort(int a[],int n,int max)
4 {
5 int count[50]={0},i,j;
6
7 for(i=0;i<n;++i)
8 count[a[i]]=count[a[i]]+1;
9
10 printf("\nSorted elements are:");
11
12 for(i=0;i<=max;++i)
13 for(j=1;j<=count[i];++j)
14 printf("%d ",i);
15 }
16
17 int main()
18 {
19 int a[50],n,i,max=0;
20 printf("Enter number of elements:");
21 scanf("%d",&n);
22 printf("\nEnter elements:")
23

for(i=0;i<n;++i)
{
scanf("%d",&a[i]);
24 if(a[i]>max)
25 max=a[i];
26 }
27
28 counting_sort(a,n,max);
29 return 0;
30 }

Output

Viva-voce Questions

Q-1 What is counting sort

Counting Sort. Counting sort is a sorting technique based on keys between a specific range. It
works by counting the number of objects having distinct key values (kind of hashing). Then doing
some arithmetic to calculate the position of each object in the output sequence.

You might also like