algorithms lab manual (scsvmv du)

66
Sri Chandrasekharendra Saraswathi Viswa Mahavidyalaya [Enathur, Kanchipuram, Tamilnadu – 631561] Department of Computer Science & Engg., Lab Manual of Algorithms Lab - B.E [CSE] Name : ________________________________________ Reg. No : ________________________________________ Class : II B.E. [CSE] Subject : EBC4AP121 – Algorithms Lab

Upload: nagasubramaniyan-sankaranarayanan

Post on 31-Dec-2015

35 views

Category:

Documents


0 download

DESCRIPTION

Algorithms for some applications

TRANSCRIPT

Page 1: Algorithms Lab Manual (SCSVMV DU)

Sri Chandrasekharendra Saraswathi Viswa

Mahavidyalaya [Enathur, Kanchipuram, Tamilnadu – 631561]

Department of Computer Science & Engg.,

Lab Manual of

Algorithms Lab - B.E [CSE]

Name : ________________________________________

Reg. No : ________________________________________

Class : II B.E. [CSE]

Subject : EBC4AP121 – Algorithms Lab

Page 2: Algorithms Lab Manual (SCSVMV DU)

INDEX

Sl.No CONTENT Page

1. Introduction to the Algorithm Analysis and Design 1

2. Platform used in the Lab 2

3. Hardware available in the lab 3

4. List of Experiments 4

5. Sample viva questions 61

6 Format of the lab record to be prepared by the students. 62

Page 3: Algorithms Lab Manual (SCSVMV DU)

1

1. INTRODUCTION TO ALGORITHM ANALYSIS AND DESIGN

An algorithm, named after the ninth century scholar Abu Jafar Muhammad Ibn Musu Al-Khowarizmi, is a set of rules for carrying out calculation either by hand or on a machine.

1. Algorithmic is a Branch of Computer Science that consists of designing and analyzing Computer algorithms The “design” pertains to

i. The description of algorithm at an abstract level by means of a pseudo language, and

ii. Proof of correctness that is, the algorithm solves the given problem in all cases.

2. The “analysis” deals with performance evaluation (complexity analysis).

The complexity of an algorithm is a function g(n) that gives the upper bound of the number of operation (or running time) performed by an algorithm when the input size is n. There are two interpretations of upper bound. Worst-case Complexity The running time for any given size input will be lower than the upper bound except possibly for some values of the input where the maximum is reached.

Average-case Complexity The running time for any given size input will be the average number of operations over all problem instances for a given size.

An algorithm has to solve a problem. An algorithmic problem is specified by describing the set of instances it must work on and what desired properties the output must have.

We need some way to express the sequence of steps comprising an algorithm. In order of increasing precision, we have English, pseudo code, and real programming languages. Unfortunately, ease of expression moves in the reverse order. In the manual to describe the ideas of an algorithm pseudo codes, algorithms and functions are used.

In the algorithm analysis and design lab various strategies such as Divide and conquer technique, greedy technique and dynamic programming techniques are used. Many sorting algorithms are implemented to analyze the time complexities.

Page 4: Algorithms Lab Manual (SCSVMV DU)

2

2. PLATFORM USED IN THE LAB

Windows XP/ Windows 7 operating system.

Software for Implementation

Using Turbo C++ Compiler

Your IDE will look like this..

Page 5: Algorithms Lab Manual (SCSVMV DU)

3

3. HARDWARE AVAILABLE IN THE LAB

HP SERVER HP Pro ML 350 G6 (TM) / Intel QUAD CORE XEON E5504 2.0 / 8 GB DDR3-1333 146 GB SAS HDD DP HDD*3 DVD ROM DRIVE HP Keyboard, Mouse 19” TFF MONITOR

HP CLIENT MACHINES Intel Core 2 Duo E7500 2.93 Ghz 4 GB DDR3 Ram / 320 GB HDD, DVD RW, HP Keyboard, HP Mouse 18.5”TFT monitor

Page 6: Algorithms Lab Manual (SCSVMV DU)

4

4. LIST OF PROGRAMS

Ex .No TITLE OF PROGRAMS

1. Write a program that implements Tower of Hanoi.

2. Write a program that implements Fibonacci series.

3. Write a program that implements insertion sort.

4. Write a program that implements Selection sort.

5. Write a program that implements Binary search.

6 Write a program that implements Merge sort

7 Write a program that implements Quick sort

8 Write a program to find the minimum and maximum value using divide

and conquer.

9 Write a program that implements knapsack using greedy method

10 Write a program that implements travelling sales person problem.

11 Write a program that implements All pair Shortest path

12 Write a program that implements N-Queen Problem

Page 7: Algorithms Lab Manual (SCSVMV DU)

5

1. TOWER OF HANOI

Problem Statement:

The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower,[1] and sometimes

pluralized) is a mathematical game or puzzle. It consists of three pegs, and a number of disks

of different sizes which can slide onto any peg. The puzzle starts with the disks in a neat

stack in ascending order of size on one peg, the smallest at the top, thus making a conical

shape.

The objective of the puzzle is to move the entire stack to another peg, obeying the following simple rules:

1. Only one disk may be moved at a time.

2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack.

3. No disk may be placed on top of a smaller disk.

With three disks, the puzzle can be solved in seven moves. The minimum number of moves required to solve a Tower of Hanoi puzzle is 2n - 1, where ‘n’ is the number of disks.

Method to solve the problem

• To move n disks from peg A to peg C with peg B as auxiliary

• First move n-1 disks recursively from peg A to peg B with peg C as auxiliary

• Move the largest disk from peg A to peg C

• Then move the n-1 disks recursively from peg B to peg C with peg A as auxiliary

• If n=1 simply move the single disk from source to destination

Page 8: Algorithms Lab Manual (SCSVMV DU)

6

Recursive algorithm to move n disks from peg A to peg C using Peg B

Algorithm TOH(n,A,B,C)

//Moves n disks from Peg A to Peg C using Peg B as auxiliary if n=1 Move A→C return else { TOH(n-1,A,C,B) Move A→C TOH(n-1,B,A,C) } Stop

Analysis:

The recursive relation for getting the number of moves is given by:

M(n)=2M(n-1)+1 for n>1

M(1)=1

Solving the recurrence relation gives

M(n)=2n-1

Page 9: Algorithms Lab Manual (SCSVMV DU)

7

Exp No: 1 TOWER OF HANOI

Date

Page 10: Algorithms Lab Manual (SCSVMV DU)

8

Page 11: Algorithms Lab Manual (SCSVMV DU)

9

Page 12: Algorithms Lab Manual (SCSVMV DU)

10

2. FIBONACCI SEQUENCE

Problem Statement:

Compute the nth Fibonacci number. “The Fibonacci sequence”

usually refers to a set of numbers that starts as {0, 1, 1, 2, 3, 5, 8,

13, 21…}. This sequence is created by following two rules:

� The first two numbers are 0 and 1.

� The next number is the sum of the two most recent numbers.

Method to solve the problem

Mathematically the n+1th Fibonacci number is given by the formula

x[n+1] = x[n] + x[n-1].

Algorithms

Recursive algorithm

Algorithm Fib(n)

//Computes the nth Fibonacci number recursively by using its definition //Input: A nonnegative integer n //Output: The nth Fibonacci number if n ≤ 1 return n else return F(n − 1) + F(n − 2)

Non Recursive algorithm Algorithm Fib(n) //Computes the nth Fibonacci number iteratively by using its definition //Input: A nonnegative integer n //Output: The nth Fibonacci number F0←0; F1←1 for i ←2 to n do {F←F0+ F1 F0 ←F1 F1 ←F} return F Analysis: The time complexity of the recursive algorithm is exponential in n The non recursive algorithm makes n − 1 additions. Hence, it is linear as a function of n

Page 13: Algorithms Lab Manual (SCSVMV DU)

11

Exp No: 2 FIBONACCI SEQUENCE

Date

Page 14: Algorithms Lab Manual (SCSVMV DU)

12

Page 15: Algorithms Lab Manual (SCSVMV DU)

13

Page 16: Algorithms Lab Manual (SCSVMV DU)

14

3. INSERTION SORT Problem Statement:

To sort an array using insertion sort. Insertion sort is a simple sorting algorithm that is

relatively efficient for small lists and mostly-sorted lists, and often is used as part of more

sophisticated algorithms. It works by taking elements from the list one by one and inserting

them in their correct position into new sorted list. The insertion sort works just like its name

suggests - it inserts each item into its proper place in the final list.

Method to solve the problem: To sort an array a[1:n], the basic idea of insertion sort is to

place the element a[j] in correct position in the sorted set a[1:j-1], for j=2. ….n.To

accommodate a[j] the elements in a[1:j-1] have to moved.

Example: Following figure shows the operation of INSERTION-SORT on the array A= (5,

2, 4, 6, 1, 3). Each part shows what happens for a particular iteration with the value of j

Algorithm:

Algorithm INSERTION_SORT (A,n) FOR j ← 2 TO n DO

{key ← A[j] //Put A[j] into the sorted sequence A[1 . . j − 1] i ← j − 1 WHILE i > 0 and A[i] > key DO

{ A[i +1] ← A[i] i ← i − 1 } A[i + 1] ← key}

Stop Analysis: The worst case time of this sorting is θ(n2 ) and best case time is θ(n )

Page 17: Algorithms Lab Manual (SCSVMV DU)

15

Exp No: 3 INSERTION SORT

Date

Page 18: Algorithms Lab Manual (SCSVMV DU)

16

Page 19: Algorithms Lab Manual (SCSVMV DU)

17

Page 20: Algorithms Lab Manual (SCSVMV DU)

18

4. SELECTION SORT

Problem Statement

To sort an array using selection sort. Selection sort is a simple sorting algorithm that is relatively in-efficient for large lists. It works by selecting the smallest/largest element from the unsorted list and placing it in the correct position of the sorted list. The selection sort works just like its name suggests - it selects the correct item and places it in its proper place in the final list.

Method to solve the problem

Effectively, the list is divided into two parts: the set of items already sorted which is built up from left to right/right to left, and the set of items remaining to be sorted, occupying the remainder of the array

Algorithm

Algorithm Selectionsort(A,n)

{ FOR j ← 2 TO length[A] i := n while i > 1 do { m ←1 max ←A[1] j←2 while j < i do { if max < A[j] then { m ← j max ←A[j]}

j←j+1 }

A[m] ←A[i] A[i] ←max i←i-1}

}

Analysis Selection sort does not depend on the data in the array. Selecting the lowest element requires scanning all n elements (this takes n − 1 comparisons) and then swapping it into the first position. Finding the next lowest element requires scanning the remaining n − 1 elements and so on. Hence the number of comparisons is (n − 1) + (n − 2) + ... + 2 + 1 = n(n − 1) / 2 ∈ Θ(n2)

Page 21: Algorithms Lab Manual (SCSVMV DU)

19

Exp No: 4 SELECTION SORT

Date

Page 22: Algorithms Lab Manual (SCSVMV DU)

20

Page 23: Algorithms Lab Manual (SCSVMV DU)

21

Page 24: Algorithms Lab Manual (SCSVMV DU)

22

5. BINARY SEARCH

Problem Statement:

This is a an efficient algorithm for searching for an element K in a sorted array using divide and conquer technique Method to solve the problem

The algorithm checks for the middle element A(m)

If K = A[m], stop (successful search); otherwise, continue searching by the same method in A[0..m-1] if K < A[m] and in A[m+1..n-1] if K > A[m] Recursive algorithm Algorithm Binsearch(A,low,high,K) if (low=high) then //Small P {if K=A[low] then return low else return -1} else { mid ← (low+high)/2

if K = A[mid] return mid

else if K < A[mid] return Binsearch(A,low,mid-1,K) else return Binsearch(A,mid+1,high,K) } Non Recursive algorithm Algorithm Binsearch(A,n,K) l ← 0; r ← n-1 while l ≤ r do m ← (l+r)/2 if K = A[m] return m else if K < A[m] r ← m-1 else l ← m+1 return -1

Analysis: The time complexity of Binary search is given by Best case θ(1) ; Average case θ(log(n)) and worst case θ(log(n))

Page 25: Algorithms Lab Manual (SCSVMV DU)

23

Exp No: 5 BINARY SEARCH

Date

Page 26: Algorithms Lab Manual (SCSVMV DU)

24

Page 27: Algorithms Lab Manual (SCSVMV DU)

25

Page 28: Algorithms Lab Manual (SCSVMV DU)

26

6. MERGE SORT

Problem Statement

To sort an array using Merge sort which uses divide and conquer technique. It takes

advantage of the ease of merging already sorted lists into a new sorted list. It starts by

comparing every two elements (i.e. 1 with 2, then 3 with 4...) and swapping them if the first

should come after the second. It then merges each of the resulting lists of two into lists of

four, then merges those lists of four, and so on; until at last two lists are merged into the final

sorted list. Of the algorithms described here, this is the first that scales well to very large lists.

Method to solve the problem

Merge sort works as follows: 1. Divide the unsorted list into two sub lists of about half the size 2. Sort each of the two sub lists 3. Merge the two sorted sub lists back into one sorted list.

Algorithm

Algorithm MergeSort(low,high) //a[low:high] is a global array to be sorted //Small(P) is true if there is only one element //to sort. In this case the list is already sorted. { if (low<high) then //if there are more than one element {

Page 29: Algorithms Lab Manual (SCSVMV DU)

27

//Divide P into subproblems //find where to split the set mid = [(low+high)/2]; //solve the subproblems. mergesort (low,mid); mergesort(mid+1,high); //combine the solutions . merge(low,mid,high); } }

Algorithm: Merging 2 sorted subarrays using auxiliary storage.

Algorithm merge(low,mid,high) //a[low:high] is a global array containing //two sorted subsets in a[low:mid] and in a[mid+1:high].The goal is to merge these 2 sets into //a single set residing in a[low:high].b[] is an auxiliary global array. { h=low; I=low; j=mid+1; while ((h<=mid) and (j<=high)) do { if (a[h]<=a[j]) then { b[I]=a[h]; h = h+1; } else { b[I]= a[j]; j=j+1; } I=I+1; } if (h>mid) then for k=j to high do { b[I]=a[k]; I=I+1; } else for k=h to mid do { b[I]=a[k]; I=I+1; } for k=low to high do a[k] = b[k]; }

Page 30: Algorithms Lab Manual (SCSVMV DU)

ANALYSIS

The straightforward version of function the sequence to the intermediate arrThe time complexity of mergesort

T(n) 2n + 2 T(n/2) and

T(1) = 0

The solution of this recursion yields

T(n) 2n log(n) O(n

A drawback of Mergesort is that it b.

28

The straightforward version of function merge requires at most 2n steps (n the sequence to the intermediate array b, and at most n steps for copying it back to array

mergesort is therefore

and

The solution of this recursion yields

n log(n))

A drawback of Mergesort is that it needs an additional space of Θ(n) for the temporary array

steps for copying steps for copying it back to array a).

) for the temporary array

Page 31: Algorithms Lab Manual (SCSVMV DU)

29

Exp No: 6 IMPLEMENTS MERGE SORT

Date

Page 32: Algorithms Lab Manual (SCSVMV DU)

30

Page 33: Algorithms Lab Manual (SCSVMV DU)

31

Page 34: Algorithms Lab Manual (SCSVMV DU)

Problem Statement:

Quick sort is a divide and conquer algorithm which relies on a partition operation: to partition

an array, using an element, called a pivot

and all greater elements are moved after it. This can be done efficiently in linear time and in

place. Then recursively sorting can be done for the lesser and greater sub l

Method to solve the problem

Select a pivot (partitioning element)

Rearrange the list so that all the elements in the first equal to the pivot and all the elements in the remaining equal to the pivot Exchange the pivot with the last element in the first (i.e., now in its final positionSort the two sub arrays recursively

32

7. QUICK SORT

Quick sort is a divide and conquer algorithm which relies on a partition operation: to partition

an element, called a pivot. All smaller elements are moved before the pivot,

and all greater elements are moved after it. This can be done efficiently in linear time and in

place. Then recursively sorting can be done for the lesser and greater sub lists.

Method to solve the problem

(partitioning element) – here, the first element

Rearrange the list so that all the elements in the first s positions are smaller than or equal to the pivot and all the elements in the remaining n-s positions are larger than or

Exchange the pivot with the last element in the first (i.e., ≤) subarray now in its final position Sort the two sub arrays recursively

Quick sort is a divide and conquer algorithm which relies on a partition operation: to partition

ll smaller elements are moved before the pivot,

and all greater elements are moved after it. This can be done efficiently in linear time and in-

ists.

positions are smaller than or ns are larger than or

) subarray — the pivot is

Page 35: Algorithms Lab Manual (SCSVMV DU)

33

Algorithm to Partition the array Algorithm Partition(A, left, right) //Partition the sub array A[l..r] using its first element as pivot p←A[l] i←l; j←r; do do i←i+1 until A[i]≥p do j←j-1 until A[j] ≤p swap (A[i],A[j]) until i≥j swap (A[i],A[j]) swap (A[l],A[j]) return j Algorithm to invoke quick sort Algorithm quicksort(A, left, right) if right > left j← partition(A, left, right+1) quicksort(A, left,j-1) quicksort(A, j+1, right) end

ANALYSIS The partition routine examines every item in the array at most once, so complexity is clearly O(n). Usually, the partition routine will divide the problem into two roughly equal sized partitions. The array of n items can be divided in to half in log2n times. This makes quicksort a O(nlogn) algorithm - equivalent to heapsort.

The most complex issue in quick sort is choosing a good pivot element; consistently poor

choices of pivots can result in drastically slower (O(n2)) performance, but if at each step we

choose the median as the pivot then it works in O(n log n).

Page 36: Algorithms Lab Manual (SCSVMV DU)

34

Exp No: 7 QUICK SORT

Date

Page 37: Algorithms Lab Manual (SCSVMV DU)

35

Page 38: Algorithms Lab Manual (SCSVMV DU)

36

Page 39: Algorithms Lab Manual (SCSVMV DU)

37

8. MAXIMUM AND MINIMUM ELEMENTS USING DIVIDE AND CONQUER

Problem Statement To find the maximum and minimum of an array of elements using divide and conquer method. Method to solve the problem If the array has more than two elements the midpoint is determined and two new sub problems are generated. When maxima and minima of these two sub problems are determined, the two are compared to achieve the solution. The situation of array of size one and two are dealt separately.

Algorithm to find the maximum and minimum items in a set of (n) elements. Algorithm MaxMin(i, j, max, min) if (i=j) then max=min=a(i) else if (i=j-1) then if (a(i)<a(j)) then max= a(j) min= a(i) else max= a(i) min= a(j) else mid= (i+j)/2 maxmin(i, mid, max, min) maxmin(mid+1, j, max1, min1) if (max<max1) then max = max1 if (min>min1) then min = min1 end Analysis If T(n) represents the number of comparisons then T(n)= T(n/2)+T(n/2)+2 n>2

= 1 for n=2 = 0 for n=1

By solving the above recurrence relation we get, T(n)=3n/2 which is less than 2n-2 in case of normal method.

However MaxMin is worse than straight forward method in terms of storage because it requires stack space for i,j,max,min,max1,min1 and return address for every recursive call.

Page 40: Algorithms Lab Manual (SCSVMV DU)

38

Exp No: 8 MAXIMUM AND MINIMUM ELEMENTS USING DIVIDE AND

CONQUER

Date

Page 41: Algorithms Lab Manual (SCSVMV DU)

39

Page 42: Algorithms Lab Manual (SCSVMV DU)

40

Page 43: Algorithms Lab Manual (SCSVMV DU)

9. KNAPSACK PROBLEM USING GREEDY METHOD

Problem Statement

– Given n objects and a knapsack where object i has a weight w

pi and the knapsack has a capacity m

– If a fraction xi

– The objective is to obtain a filling of knapsack maximizing the total profit Method to solve the problem

Problem formulation

Maximize ∑pixi

Subject to ∑wixi ≤ M

and 0 ≤ xi ≤ 1, 1 ≤i ≤n Greedy approximation algorithm The greedy approximation algorithm to solve the knapsack problem sorts the increasing order of ratio of profit to weightsack, starting from the first element (the greatest) until there is no longer space in the sack for more Algorithm Greedy Knapsack void GreedyKnapsack(float m, int n) // p[1:n] and w[1:n] contain the profits and weightssuch that p[i]/w[i] >= p[i+1]/w[i+1]. m is the knapsack { for (i←1 to n) do x[i] = 0.0; // Initialize x. U ← m;

41

9. KNAPSACK PROBLEM USING GREEDY METHOD

Given n objects and a knapsack where object i has a weight w

and the knapsack has a capacity m

of object i placed into knapsack, a profit pi

The objective is to obtain a filling of knapsack maximizing the total profit

Method to solve the problem

Greedy approximation algorithm

greedy approximation algorithm to solve the knapsack problem sorts the ratio of profit to weight (pi/wi) and then proceeds to insert them into the

sack, starting from the first element (the greatest) until there is no longer space in the sack for

Algorithm Greedy Knapsack

void GreedyKnapsack(float m, int n) // p[1:n] and w[1:n] contain the profits and weights / respectively of the n objects ordered

p[i]/w[i] >= p[i+1]/w[i+1]. m is the knapsack size and x[1:n] is the solution vector.

ize x.

9. KNAPSACK PROBLEM USING GREEDY METHOD

Given n objects and a knapsack where object i has a weight wi and profit

ixi is earned

The objective is to obtain a filling of knapsack maximizing the total profit

greedy approximation algorithm to solve the knapsack problem sorts the objects in and then proceeds to insert them into the

sack, starting from the first element (the greatest) until there is no longer space in the sack for

/ respectively of the n objects ordered size and x[1:n] is the solution vector.

Page 44: Algorithms Lab Manual (SCSVMV DU)

42

for (i←1 to n) do { if (w[i] > U) break; x[i] ← 1.0 U ← U - w[i] } if (i <= n) x[i] ←U/w[i] } Analysis:

Sorting: O(n log n) using fast sorting algorithm like merge sort GreedyKnapsack: O(n) So, total time is O(n log n)

Page 45: Algorithms Lab Manual (SCSVMV DU)

43

Exp No: 9 KNAPSACK USING GREEDY METHOD

Date

Page 46: Algorithms Lab Manual (SCSVMV DU)

44

Page 47: Algorithms Lab Manual (SCSVMV DU)

45

Page 48: Algorithms Lab Manual (SCSVMV DU)

46

10. TRAVELLING SALES PERSON PROBLEM (TSP)

Problem Statement:

Given a set of cities and the distance between each possible pair, the Travelling Salesman Problem is to find the best possible way of ‘visiting all the cities exactly once and returning to the starting point. This problem is solved using Dynamic Programming technique.

Method to solve the problem

First, find out all (n -1)! Possible solutions, where n is the number of cities.

Next, determine the minimum cost by finding out the cost of everyone of these (n -1)! solutions. Finally, keep the one with the minimum cost.

• Let g(i,S) be the length of the shortest path starting from vertex i going through all vertices in S and terminating at vertex 1

• g(1,V-{1}) is the length of the optimal sales person tour. • From the principle of optimality

– g(1,V-{1})=min{ c 1k +g(k,V-{1,k})} for 2 ≤k ≤n – In general, – g(i,S)=min{ ci,j +g(j,S-{j})} for j in S

Page 49: Algorithms Lab Manual (SCSVMV DU)

47

Algorithm Function TSP(G,n) for all S, subset of {2,3,……n} with ||S||=s do { for s=0 to n-2 do { for all i not in S do { if s=0 then g(i,S})=ci1

else g(i,S)=min i≠j, j in S {c i,j +g(j,S-{j})} } } } opt=min 2≤k ≤n { c1k +g(k,V-{1,k})} Return (opt)

Analysis

If we try to determine the solution of this problem systematically, we would end up with (n - 1)! Possible solutions. For example if there were 21 cities the steps required are (n - 1)! = (21 - 1)! = 20! Steps

Page 50: Algorithms Lab Manual (SCSVMV DU)

48

Exp No: 10 TRAVELLING SALES PERSON PROBLEM

Date

Page 51: Algorithms Lab Manual (SCSVMV DU)

49

Page 52: Algorithms Lab Manual (SCSVMV DU)

50

Page 53: Algorithms Lab Manual (SCSVMV DU)

51

11. ALL PAIR SHORTEST PATH

Problem Statement:

Given a directed, connected weighted graph G(V,E), for each edge ⟨u,v⟩∈E, a weight w(u,v) is associated with the edge. The all pairs of shortest paths problem (APSP) is to find a shortest path from u to v for every pair of vertices u and v in V. This problem is solved using Dynamic Programming technique. Method to solve the problem

The input is an n×n matrix W=( wij ). w(i,j)={ 0 if i=j the weight of the directed edge ⟨i,j⟩ if i≠j and ⟨i,j⟩∈E ∞ if i≠j and ⟨i,j⟩∉E

The Floyd-Warshall Algorithm Floyd-Warshall's algorithm is based upon the observation that a path linking any two vertices u and v may have zero or more intermediate vertices. The algorithm begins by disallowing all intermediate vertices. In this case, the partial solution is simply the initial weights of the graph or infinity if there is no edge. The algorithm proceeds by allowing an additional intermediate vertex at each step. For each introduction of a new intermediate vertex x, the shortest path between any pair of vertices u and v, x,u,v∈V, is the minimum of the previous best estimate of δ(u,v), or the combination of the paths from u→x and x→v.

δ(u,v)←min(δ(u,v),δ(u,x)+δ(x,v)) Algorithm Algorithm FLOYD-WARSHALL (W) 1 n ← rows [W] 2 D(0) ← W 3 for k ← 1 to n 4 do for i ← 1 to n 5 do for j ← 1 to n 6 do dij (k) ← MIN ( dij (k-1) , dik (k-1) + dkj (k-1) ) 7 return D(n) Analysis The time complexity of the algorithm is O( n3 ).

Page 54: Algorithms Lab Manual (SCSVMV DU)

52

Exp No: 11 ALL PAIR SHORTEST PATH

Date

Page 55: Algorithms Lab Manual (SCSVMV DU)

53

Page 56: Algorithms Lab Manual (SCSVMV DU)

54

Page 57: Algorithms Lab Manual (SCSVMV DU)

55

12. N-QUEEN PROBLEM

Problem Statement To place N queens on a chessboard in such a way that no queen can attack any other using backtracking method.

Method to solve the problem

• A queen can attack another queen if it exists in the same row, column or diagonal as the queen.

• This problem can be solved by trying to place the first queen, then the second queen so that it cannot attack the first, and then the third so that it is not conflicting with previously placed queens

• The solution for N=8 is a vector of length 8 • (x(1), x(2), x(3), ...., x(8)). • x(i) corresponds to the column in the ith row where we should place the i-th

queen. All the x(i)s should be distinct since no two queens should be placed in the same column

• The solution is to build a partial solution element by element until it is complete. • We should backtrack in case we reach to a partial solution of length k, that we

couldn't expand any more

Algorithm

Algorithm place (k,I) //return true if a queen can be placed in k th row and I th column. otherwise it returns false . //X[] is a global array whose first k-1 values have been set. Abs returns the absolute value of r. { For j=1 to k-1 do If ((X [j]=I) //two in same column. Or (abs (X [j]-I)=Abs (j-k))) Then return false; Return true; }

Page 58: Algorithms Lab Manual (SCSVMV DU)

56

Algorithm Nqueen (k,n) //using backtracking it prints all possible positions of n queens in ‘n*n’ chessboard. { For I=1 to n do { If place (k,I) then { X [k]=I; If (k=n) then write (X [1:n]); Else nquenns(k+1,n) ; } } } Analysis For 8X8 chess board there are 64C8 possible ways to place 8 pieces. However by allowing only placements of queens on distinct rows and columns we require the examination of at most 8! 8-tuples.

Page 59: Algorithms Lab Manual (SCSVMV DU)

57

Exp No: 12 N – QUEEN PROBLEM

Date

Page 60: Algorithms Lab Manual (SCSVMV DU)

58

Page 61: Algorithms Lab Manual (SCSVMV DU)

59

Page 62: Algorithms Lab Manual (SCSVMV DU)

60

5. FORMAT OF THE LAB RECORDS TO BE PREPARED BY THE

STUDENTS

The students are required to maintain the lab records as per the instructions:

1. All the record files should have a cover page as per the format.

2. All the record files should have an index as per the format.

3. All the records should have the following :

I. Experiment No II. Date

III. Program Name IV. Aim V. Algorithm or the Procedure to be followed.

VI. Program VII. Output

Page 63: Algorithms Lab Manual (SCSVMV DU)

61

6. SAMPLE VIVA QUESTIONS

1. What is an algorithm? 2. What is a randomized algorithm? 3. Define Omega notation. 4. Define Big-O notation. 5. Define Theta notation. 6. What are loop invariants? 7. What is a Pseudocode? 8. What are the worst case and average case running time of insertion sort? 9. Which technique is used to sort elements in merge sort? 10. What is the running time of merge sort? 11. How merge sort is different from quick sort? 12. What is the worst case running time of quick sort? 13. What are the differences between dynamic and greedy algorithms? 14. Dijkstra algorithm can take into account the negative edge weigthts.'Is the statement

true? 15. Define minimum spanning tree.' 16. Name any algorithm for finding the minimum spanning tree. 17. Compare Prim's and Kruskal's algorithm. 18. What are NP-complete problems. 19. Name some NPC problems. 20. Define Travelling salesman problem.

Page 64: Algorithms Lab Manual (SCSVMV DU)

62

SRI CHANDRASEKHARENDRA SARASWATHI

VISWA MAHAVIDYALAYA ( University Established under section 3 of UGC Ac t 1956)

ENATHUR, KANCHIPURAM – 631 561

LABORATORY RECORD

Name :

Reg. No :

Class : II YEAR BE[CSE]

Subject : EBC4AP121 – Algorithms Lab

Page 65: Algorithms Lab Manual (SCSVMV DU)

63

SRI CHANDRASEKHARENDRA SARASWATHI VISWA MAHAVIDYALAYA

( University Established under section 3 of UGC Ac t 1956)

ENATHUR, KANCHIPURAM – 631 561

BONAFIDE CERTIFICATEBONAFIDE CERTIFICATEBONAFIDE CERTIFICATEBONAFIDE CERTIFICATE

This is to Certify that this is the bonafide record of work done by

Mr/Ms.________________________________________________________,

with Reg.No.___________________ of II Year B.E [CSE] in the

Algorithms during the year 2013-2014.

Station :_____________

Date :_____________

Staff-in-charge Head of the Department Submitted for the Practical Examination held on______________ Internal Examiner External Examiner

Page 66: Algorithms Lab Manual (SCSVMV DU)

64

INDEXINDEXINDEXINDEX

Exp.

No.

Date

TITLE

Page No

Sign