• No results found

INDEX. 1 Write recursive program which computes the nth Fibonacci number,

N/A
N/A
Protected

Academic year: 2021

Share "INDEX. 1 Write recursive program which computes the nth Fibonacci number,"

Copied!
68
0
0

Loading.... (view fulltext now)

Full text

(1)

P a g e | 1 Department of Computer Science & Engineering GEC

INDEX

S.No

PROGRAMS LIST

Page no

1 Write recursive program which computes the nth Fibonacci number, for appropriate values of n.

Analyze behavior of the program Obtain the frequency count of the statement for various values of n.

3

2 Write recursive program for the following

a) Write recursive C program for calculation of Factorial of an integer 4 b) Write recursive C program for calculation of GCD (n, m) 5 c) Write recursive C program for Towers of Hanoi : N disks are to be

transferred from peg S to peg D with Peg I as the intermediate peg.

7 3 a) Write C programs that use both recursive and non recursive functions to

perform Linear search for a Key value in a given list.

11 b) Write C programs that use both recursive and non recursive functions to

perform Binary search for a Key value in a given list.

12 c) Write C programs that use both recursive and non recursive functions to

perform Fibonacci search for a Key value in a given list.

13 4 a) Write C programs that implement Bubble sort, to sort a given list of

integers in ascending order

15 b) Write C programs that implement Quick sort, to sort a given list of

integers in ascending order

15 c) Write C programs that implement Insertion sort, to sort a given list of

integers in ascending order

16 5 a) Write C programs that implement Heap sort, to sort a given list of

integers in ascending order

18 b) Write C programs that implement Radix sort, to sort a given list of

integers in ascending order

22 c) Write C programs that implement Merge sort, to sort a given list of

integers in ascending order

25 6 a) Write C programs that implement stack (its operations) using arrays 27 b) Write C programs that implement stack (its operations) using Linked list 30 7 a) Write a C program that uses Stack operations to Convert infix expression

into postfix expression

34 b) Write C programs that implement Queue (its operations) using arrays. 36 c) Write C programs that implement Queue (its operations) using linked

lists

39 8 a) Write a C program that uses functions to create a singly linked list 45

b) Write a C program that uses functions to perform insertion operation on a singly linked list

48 c) Write a C program that uses functions to perform deletion operation on 50

(2)

P a g e | 2 Department of Computer Science & Engineering GEC

a singly linked list

9 d) Adding two large integers which are represented in linked list fashion. 53 e) Write a C program to reverse elements of a single linked list. 54 f) Write a C program to store a polynomial expression in memory using

linked list

55 g) Write a C program to representation the given Sparse matrix using

arrays.

57 10 a) Write a C program to Create a Binary Tree of integers 59

b) Write a recursive C program, for Traversing a binary tree in preorder, in order and post order.

61

11 a) Write a C program to Create a BST 63

b) Write a C program to insert a note into a BST. 65 c) Write a C program to delete a note from a BST. 66 12 a) Write a C program to compute the shortest path of a graph using

Dijkstra’s algorithm

67 b) Write a C program to find the minimum spanning tree using Warshall’s

Algorithm

69

ADD ON PROGRAMS :

1 Write a C program on Circular Queue operations 105 2 Write a C program on Evaluation on Postfix Expression 107 3 Write a C program search the elements using Breadth First Search Algorithm &

Depth First Search Algorithm

108

4

Write a C program to perform various operations i.e., insertions and deletions on AVL trees.

(3)

P a g e | 3 Department of Computer Science & Engineering GEC

Exercise 1:

Write recursive program which computes the nth Fibonacci number, for appropriate values of n.

Analyze behavior of the program Obtain the frequency count of the statement for various values of n.

DESCRIPTION:

C Programming Language: Using Recursion to Print the Fibonacci Series? The Fibonacci series

0, 1, 1, 2, 3, 5, 8, 13, 21, …..

Begins with the terms 0 and 1 and has the property that each succeeding term is the sum of the two preceding terms.

For this problem, we are asked to write a recursive function fib (n) that calculates the nth Fibonacci number. Recursion MUST be used.

In an earlier problem, we where asked to do the exact same thing, except we where to NOT use recursion. For that problem, I used the following code (between the dotted lines):

ALGORITHM :

1. Start.

2. Get the number n up to which Fibonacci series is generated. 3.Call to the function fib.

(4)

P a g e | 4 Department of Computer Science & Engineering GEC

4.stop

Algorithm fib 1.start

2.if n=0 or 1 then return n 3.else return fib(n-1)+fib(n-2) 4. Stop.

(5)

P a g e | 5 Department of Computer Science & Engineering GEC

Exercise 2:

a). Write recursive C program for calculation of Factorial of an integer

Recursion :

Procedures which call themselves within the body of their lambda expression are said to be recursive. In general, recursive procedures need a terminating condition (otherwise they will run forever) and a recursive step (describing how the computation should proceed). We will use one of MzScheme's procedures trace to illustrate the behavior of recursive procedures. The procedure trace shows the intermediate steps as the recursion proceeds as well as the intermediate values returned.

For example, let us define a procedure for counting the factorial of a number. We know that equals 1 and we will use this as our terminating condition. Apart from that, we know that is the same as , which gives us our recursive step. We are now ready to define the procedure itself:

(define fact (lambda (n)

(if (= n 0) ; the terminating condition 1 ; returning 1

(* n (fact (- n 1)))))) ; the recursive step

Let' see what happens if we try to compute the factorial of 7 by using the procedure trace: > (fact 7) 5040 > (trace fact) (fact) > (fact 7) |(fact 7) | (fact 6) | |(fact 5) | | (fact 4) | | |(fact 3) | | | (fact 2) | | | |(fact 1) | | | | (fact 0) | | | | 1 | | |6 | | 24 | |120 | 720 |5040 5040 > (untrace fact) (fact)

(6)

P a g e | 6 Department of Computer Science & Engineering GEC

ALGORITHM :

1. Start.

2. Get the number n to which Fcatorial value is to be generated. 3. Call to the function fact.

4.Stop

Algorithm fact 1.Start

2.if n=0 or 1 then return 1 3.Else return n*fact(n-1) 4.Stop

(7)

P a g e | 7 Department of Computer Science & Engineering GEC

b). Write recursive C program for calculation of GCD (n, m)

ALGORITHM :

The GCD algorithm:

Given m,n find gcd(m,n)

We proved in class that the gcd can be found by repeatedly applying the division algorithm: a = bq + r. We start with a=m, b=n. The next pair is (b,r) [the quotient is not needed here]. We continue replacing a by the divisor and b by the

remainder until we get a remainder 0. The last non-zero remainder is the gcd. This algorithm can be performed on a spreadsheet:

A B C 1 m n 2 123456 654321 3 a b r 4 123456 654321 123456 5 654321 123456 37041 6 123456 37041 12333 7 37041 12333 42 8 12333 42 27 9 42 27 15 10 27 15 12 11 15 12 3 12 12 3 0 13 3 0 #DIV/0! 14 0 #DIV/0! #DIV/0! A B C 1 m n 2 123456 3 654321

4 =A2 =B2 =MOD (A4,B4)

5 =B4 =C4 =MOD (A5,B5) 6 =B5 =C5 =MOD (A6,B6) 7 =B6 =C6 =MOD (A7,B7) 8 =B7 =C7 =MOD (A8,B8) 9 =B8 =C8 =MOD (A9,B9) 10 =B9 =C9 =MOD (A10,B10) 11 =B10 =C10 =MOD (A11,B11) 12 =B11 =C11 =MOD (A12,B12) 13 =B12 =C12 =MOD (A13,B13) 14 =B13 =C13 =MOD (A14,B14)

Once row 5 is entered, it is copied to all lower rows. The spreadsheet automatically updates the formulas (that is what spreadsheets do!). A new pair of numbers can be entered in A2 and B2. Note that when a zero remainder occurs, the spreadsheet gives an error message on the following line.

(8)

P a g e | 8 Department of Computer Science & Engineering GEC

c). Write recursive C program for Towers of Hanoi: N disks are to be transferred from peg S to peg D with Peg I as the intermediate peg.

DESCRIPTION:

How to solve the Towers of Hanoi puzzle

The Classical Towers of Hanoi - an initial position of all disks

is on post 'A'.

Fig. 1

The solution of the puzzle is to build the tower on post 'C'.

Fig. 2

The Arbitrary Towers of Hanoi - at start, disks can be in any

position provided that a bigger disk is never on top of the smaller one (see Fig. 3). At the end, disks should be in another arbitrary position. * )

Fig. 3

(9)

P a g e | 9 Department of Computer Science & Engineering GEC

'Solution' ≡ shortest path

Recursive Solution:

1. Identify biggest discrepancy (=disk N) 2. If moveable to goal peg Then move Else

3. Subgoal: set-up (N−1)-disk tower on non-goal peg. 4. Go to 1. ...

Solving the Tower of Hanoi - 'regular' to 'perfect'

Let's start thinking how to solve it.

Let's, for the sake of clarity, assume that our goal is to set a 4 disk-high tower on peg 'C' - just like in the classical Towers of Hanoi (see Fig. 2).

Let's assume we 'know' how to move a 'perfect' 3 disk-high tower.

Then on the way of solving there is one special setup. Disk 4 is on peg 'A' and the 3 disk-high tower is on peg 'B' and target peg 'C' is empty.

Fig. 4

From that position we have to move disk 4 from 'A' to 'C' and move by some magic the 3 disk-high tower from 'B' to 'C'. So think back. Forget the disks bigger than 3.

Disk 3 is on peg 'C'. We need disk 3 on peg 'B'. To obtain that, we need disk 3 in place where it is now, free peg 'B' and disks 2 and 1 stacked on peg 'A'. So our goal now is to put disk 2 on

(10)

P a g e | 10 Department of Computer Science & Engineering GEC

peg 'A'.

Fig. 5

Forget for the moment disk 3 (see Fig. 6). To be able to put disk 2 on peg 'A' we need to empty peg 'A' (above the thin blue line), disks smaller than disk 2 stacked on peg 'B'. So, our goal now is to put disk 1 on peg 'B'.

As we can see, this is an easy task because disk 1 has no disk above it and peg 'B' is free.

Fig. 6 So let's move it.

Fig. 7

The steps above are made by the algorithm implemented in

Towers of Hanoi when one clicks the "Help me" button. This button-function makes analysis of the current position and generates only one single move which leads to the solution. It is by design.

When the 'Help me' button is clicked again, the algorithm repeats all steps of the analysis starting from the position of the biggest disk - in this example disk 4 - and generates the

(11)

P a g e | 11 Department of Computer Science & Engineering GEC /*A recu rsiv e c prog ram for towe rs of hano i: N disk s are to be

next move - disk 2 from peg 'C' to peg 'A'.

Fig. 8

If one needs a recursive or iterative algorithm which generates the series of moves for solving arbitrary Towers of Hanoi then one should use a kind of back track programming, that is to remember previous steps of the analysis and not to repeat the analysis of the Towers from the ground.

(12)

P a g e | 12 Department of Computer Science & Engineering GEC

Exercise 3:

a). Write C programs that use both recursive and non recursive functions to perform Linear search for a Key value in a given list.

DESCRIPTION:

If the data is sorted, a binary search may be done. Variables Lb and Ub keep track of the lower bound and upper bound of the array, respectively. We begin by examining the middle element of the array. If the key we are searching for is less than the middle element, then it must reside in the top half of the array. Thus, we set Ub to (M – 1). This restricts our next iteration through the loop to the top half of the array. In this way, each iteration halves the size of the array to be searched.

For example, the first iteration will leave 3 items to test. After the second iteration, there will be one item left to test. Therefore it takes only three iterations to find any number.

This is a powerful method. Given an array of 1023 elements, we can narrow the search to 511 elements in one comparison. After another comparison, and we‟re looking at only 255 elements. In fact, we can search the entire array in only 10 comparisons. In addition to searching, we may wish to insert or delete entries. Unfortunately, an array is not a good arrangement for these operations. For example, to insert the number 18, we would need to shift A[3]…A[6] down by one slot. Then we could copy number 18 into A[3].

A similar problem arises when deleting numbers. To improve the efficiency of insert and delete operations, linked lists may be used.

ALGORITHM :

Linear Search ( ):

Description: Here A is an array having N elements. ITEM is the value to be searched. 1. Repeat for J = 1 to N

2. If (ITEM == A [J]) Then 3. Print: ITEM found at location J

(13)

P a g e | 13 Department of Computer Science & Engineering GEC

4. Return [End of If]

[End of For Loop] 5. If (J > N) Then

6. Print: ITEM doesn‟t exist [End of If]

(14)

P a g e | 14 Department of Computer Science & Engineering GEC

b).Write C programs that use both recursive and non recursive functions to perform Binary search for a Key value in a given list.

ALGORITHM :

Binary Search ( ):

Description: Here A is a sorted array having N elements. ITEM is the value to be searched. BEG denotes first element and END denotes last element in the array. MID denotes the middle value.

1. Set BEG = 1 and END = N 2. Set MID = (BEG + END) / 2

3. Repeat While (BEG <= END) and (A[MID] ? ITEM) 4. If (ITEM < A[MID]) Then

5. Set END = MID – 1 6. Else

7. Set BEG = MID + 1 [End of If]

8. Set MID = (BEG + END) / 2 [End of While Loop]

9. If (A[MID] == ITEM) Then

10. Print: ITEM exists at location MID 11. Else

12. Print: ITEM doesn‟t exist [End of If]

(15)

P a g e | 15 Department of Computer Science & Engineering GEC

c).Write C programs that use both recursive and non recursive functions to perform Fibonacci search for a Key value in a given list.

ALGORITHM :

Let Fk represent the k-th Fibonacci number where Fk+2=Fk+1 + Fk for k>=0 and F0 = 0,

F1 = 1. To test whether an item is in a list of n = Fm ordered numbers, proceed as follows:

1. Set k = m.

2. If k = 0, finish - no match.

3. Test item against entry in position Fk-1.

4. If match, finish.

5. If item is less than entry Fk-1, discard entries from positions Fk-1 + 1 to n. Set k = k - 1

and go to 2.

6. If item is greater than entry Fk-1, discard entries from positions 1 to Fk-1. Renumber

remaining entries from 1 to Fk-2, set k = k - 2 and go to 2.

If n is not a Fibonacci number, then let Fm be the smallest such number >n, augment the

original array with Fm-n numbers larger than the sought item and apply the above algorithm

(16)

P a g e | 16 Department of Computer Science & Engineering GEC

Exercise 4:

a).Write C programs that implement Bubble sort, to sort a given list of integers in ascending order

ALGORITHM:

step1: take first two elements of a list and compare them

step2: if the first elements grater than second then interchange else keep the values as it step3: repeat the step 2 until last comparison takes place

(17)

P a g e | 17 Department of Computer Science & Engineering GEC

b).Write C programs that implement Quick sort, to sort a given list of integers in ascending order

ALGORITHM:

step1: take first a list of unsorted values step2: take firstelement as 'pivot'

step3: keep the firstelement as 'pivot' and correct its position in the list step4: divide the list into two based on first element

(18)

P a g e | 18 Department of Computer Science & Engineering GEC

c).Write C programs that implement Insertion sort, to sort a given list of integers in ascending order

ALGORITHM:

step1: take a list of values

step2: compare the first two elements of a list if first element is greaterthan second interchange it else keep the list as it is.

step3: now take three elements from the list and sort them as follows Step4::reapeat step 2 to 3 until the list is sorted.

(19)

P a g e | 19 Department of Computer Science & Engineering GEC

Exercise 5:

a). Write C programs that implement Heap sort, to sort a given list of integers in ascending order

Heap Sort Technique:

Heap sort algorithm, as the name suggests, is based on the concept of heaps. It begins by constructing a special type of binary tree, called heap, out of the set of data which is to be sorted.

Note:

A Heap by definition is a special type of binary tree in which each node is greater than any of its descendants. It is a complete binary tree.

A semi-heap is a binary tree in which all the nodes except the root possess the heap property.

If N be the number of a node, then its left child is 2*N and the right child 2*N+1.

The root node of a Heap, by definition, is the maximum of all the elements in the set of data, constituting the binary tree. Hence the sorting process basically consists of extracting the root node and reheaping the remaining set of elements to obtain the next largest element till there are no more elements left to heap. Elementary implementations usually employ two arrays, one for the heap and the other to store the sorted data. But it is possible to use the same array to heap the unordered list and compile the sorted list. This is usually done by swapping the root of the heap with the end of the array and then excluding that element from any

subsequent reheaping.

Significance of a semi-heap - A Semi-Heap as mentioned above is a Heap except that the root does not possess the property of a heap node. This type of a heap is significant in the

discussion of Heap Sorting, since after each "Heaping" of the set of data, the root is extracted and replaced by an element from the list. This leaves us with a Semi-Heap. Reheaping a Semi-Heap is particularily easy since all other nodes have already been heaped and only the root node has to be shifted downwards to its right position. The following C function takes care of reheaping a set of data or a part of it.

(20)

P a g e | 20 Department of Computer Science & Engineering GEC void downHeap(int a[], int root, int bottom)

{

int maxchild, temp, child; while (root*2 < bottom) { child = root * 2 + 1; if (child == bottom) { maxchild = child; } else { if (a[child] > a[child + 1]) maxchild = child; else maxchild = child + 1; } if (a[root] < a[maxchild]) { temp = a[root]; a[root] = a[maxchild]; a[maxchild] = temp; } else return; root = maxchild; } }

In the above function, both root and bottom are indices into the array. Note that, theoritically speaking, we generally express the indices of the nodes starting from 1 through size of the array. But in C, we know that array indexing begins at 0; and so the left child is

child = root * 2 + 1

/* so, for eg., if root = 0, child = 1 (not 0) */

In the function, what basically happens is that, starting from root each loop performs a check for the heap property of root and does whatever necessary to make it conform to it. If it does already conform to it, the loop breaks and the function returns to caller. Note that the function assumes that the tree constituted by the root and all its descendants is a Semi-Heap.

Now that we have a downheaper, what we need is the actual sorting routine.

void heapsort(int a[], int array_size) {

int i;

for (i = (array_size/2 -1); i >= 0; --i) {

(21)

P a g e | 21 Department of Computer Science & Engineering GEC }

for (i = array_size-1; i >= 0; --i) { int temp; temp = a[i]; a[i] = a[0]; a[0] = temp; downHeap(a, 0, i-1); } }

Note that, before the actual sorting of data takes place, the list is heaped in the for loop

starting from the mid element (which is the parent of the right most leaf of the tree) of the list.

for (i = (array_size/2 -1); i >= 0; --i) {

downHeap(a, i, array_size-1); }

Following this is the loop which actually performs the extraction of the root and creating the sorted list. Notice the swapping of the ith element with the root followed by a reheaping of the list.

for (i = array_size-1; i >= 0; --i) { int temp; temp = a[i]; a[i] = a[0]; a[0] = temp; downHeap(a, 0, i-1); }

The following are some snapshots of the array during the sorting process. The unodered list - 8 6 10 3 1 2 5 4

After the initial heaping done by the first for loop. 10 6 8 4 1 2 5 3

Second loop which extracts root and reheaps. 8 6 5 4 1 2 3 10 } pass 1

6 4 5 3 1 2 8 10 } pass 2 5 4 2 3 1 6 8 10 } pass 3 4 3 2 1 5 6 8 10 } pass 4

(22)

P a g e | 22 Department of Computer Science & Engineering GEC

b).Write C programs that implement Radix sort, to sort a given list of integers in ascending order

Radix Sorting :

The bin sorting approach can be generalized in a technique that is known as radix sorting. An example

Assume that we have n integers in the range (0,n2) to be sorted. (For a bin sort, m = n2, and we would have an O(n+m) = O(n2) algorithm.) Sort them in two phases:

1. Using n bins, place ai into bin ai mod n,

2. Repeat the process using n bins, placing ai into bin floor(ai/n), being careful to

append to the end of each bin.

This results in a sorted list.

As an example, consider the list of integers:

36 9 0 25 1 49 64 16 81 4

n is 10 and the numbers all lie in (0,99). After the first phase, we will have:

Bin 0 1 2 3 4 5 6 7 8 9 Content 0 1 81 - - 64 4 25 36 16 - - 9 49

Note that in this phase, we placed each item in a bin indexed by the least significant decimal digit.

Repeating the process, will produce:

Bin 0 1 2 3 4 5 6 7 8 9 Content 0 1 4 9 16 25 36 49 - 64 - 81

-In this second phase, we used the leading decimal digit to allocate items to bins, being careful to add each item to the end of the bin.

We can apply this process to numbers of any size expressed to any suitable base or radix.

(23)

P a g e | 23 Department of Computer Science & Engineering GEC

We can further observe that it's not necessary to use the same radix in each phase, suppose that the sorting key is a sequence of fields, each with bounded ranges, eg the key is a date using the structure:

typedef struct t_date { int day;

int month; int year; } date;

If the ranges for day and month are limited in the obvious way, and the range for year is suitably constrained, eg 1900 < year <= 2000, then we can apply the same

procedure except that we'll employ a different number of bins in each phase. In all cases, we'll sort first using the least significant "digit" (where "digit" here means a field with a limited range), then using the next significant "digit", placing each item after all the items already in the bin, and so on.

Assume that the key of the item to be sorted has k fields, fi|i=0..k-1, and that each fi has si discrete

values, then a generalised radix sort procedure can be written:

radixsort( A, n ) { for(i=0;i<k;i++) {

for(j=0;j<si;j++) bin[j] = EMPTY;

O(si) for(j=0;j<n;j++) {

move Ai

to the end of bin[Ai->fi]

}

O(n)

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

concatenate bin[j] onto the end of A; }

}

O(si)

(24)

P a g e | 24 Department of Computer Science & Engineering GEC

Now if, for example, the keys are integers in (0,bk-1), for some constant k, then the keys can be viewed as k-digit base-b integers.

Thus, si = b for all i and the time complexity becomes O(n+kb) or O(n). This result depends on k

being constant.

If k is allowed to increase with n, then we have a different picture. For example, it takes log2n

binary digits to represent an integer <n. If the key length were allowed to increase with n, so that

k = logn, then we would have:

.

Another way of looking at this is to note that if the range of the key is restricted to (0,bk-1), then we will be able to use the radix sort approach effectively if we allow duplicate keys when n>bk. However, if we need to have unique keys, then k must increase to at least logbn. Thus, as n

increases, we need to have logn phases, each taking O(n) time, and the radix sort is the same as quick sort!

(25)

P a g e | 25 Department of Computer Science & Engineering GEC

c).Write C programs that implement Merge sort, to sort a given list of integers in ascending order

Algorithm to Sort an Array using MERGE SORT Merge Sort ( A, BEG, END ):

Description: Here A is an unsorted array. BEG is the lower bound and END is the upper bound.

1. If (BEG < END) Then 2. Set MID = (BEG + END) / 2 3. Call Merge Sort (A, BEG, MID) 4. Call Merge Sort (A, MID + 1, END) 5. Call Merge Array (A, BEG, MID, END) [End of If]

6. Exit

Merge Array ( A, BEG, MID, END )

Description: Here A is an unsorted array. BEG is the lower bound, END is the upper bound and MID is the middle value of array. B is an empty array.

1. Repeat For I = BEG to END

2. Set B[I] = A[I] [Assign array A to B] [End of For Loop]

3. Set I = BEG, J = MID + 1, K = BEG 4. Repeat While (I <= MID) and (J <= END)

5. If (B[I] <= B[J]) Then [Assign smaller value to A] 6. Set A[K] = B[I]

7. Set I = I + 1 and K = K + 1 8. Else

9. Set A[K] = B[J]

10. Set J = J + 1 and K = K + 1 [End of If]

(26)

P a g e | 26 Department of Computer Science & Engineering GEC

11. If (I <= MID) Then [Check whether first half 12. Repeat While (I <= MID) has exhausted or not] 13. Set A[K] = B[I]

14. Set I = I + 1 and K = K + 1 [End of While Loop]

15. Else

16. Repeat While (J <= END) 17. Set A[K] = B[J]

18. Set J = J + 1 and K = K + 1 [End of While Loop]

[End of If] 19. Exit

(27)

P a g e | 27 Department of Computer Science & Engineering GEC

Exercise 6:

a) Write C programs that implement stack (its operations) using arrays

Algorithm to Push Item into Stack

Push ( ):

Description: Here STACK is an array with MAX locations. TOP points to the top most element and ITEM is the value to be inserted.

1. If (TOP == MAX) Then [Check for overflow] 2. Print: Overflow

3. Else

4. Set TOP = TOP + 1 [Increment TOP by 1]

5. Set STACK[TOP] = ITEM [Assign ITEM to top of STACK] 6. Print: ITEM inserted

[End of If] 7. Exit

Algorithm to Pop Item from Stack Pop ( ):

Description: Here STACK is an array with MAX locations. TOP points to the top most element.

1. If (TOP == 0) Then [Check for underflow] 2. Print: Underflow

3. Else

4. Set ITEM = STACK[TOP] [Assign top of STACK to ITEM] 5. Set TOP = TOP - 1 [Decrement TOP by 1]

6. Print: ITEM deleted [End of If]

(28)

P a g e | 28 Department of Computer Science & Engineering GEC

b) Write C programs that implement stack (its operations) using Linked list Algorithm:

Algorithm to Push Item into Stack Push ( ):

Description: Here STACK is an array with MAX locations. TOP points to the top most element and ITEM is the value to be inserted.

1. If (TOP == MAX) Then [Check for overflow] 2. Print: Overflow

3. Else

4. Set TOP = TOP + 1 [Increment TOP by 1]

5. Set STACK[TOP] = ITEM [Assign ITEM to top of STACK] 6. Print: ITEM inserted

[End of If] 7. Exit

Algorithm to Pop Item from Stack Pop ( ):

Description: Here STACK is an array with MAX locations. TOP points to the top most element.

1. If (TOP == 0) Then [Check for underflow] 2. Print: Underflow

3. Else

4. Set ITEM = STACK[TOP] [Assign top of STACK to ITEM] 5. Set TOP = TOP - 1 [Decrement TOP by 1]

6. Print: ITEM deleted [End of If]

(29)

P a g e | 29 Department of Computer Science & Engineering GEC

Exercise 7:

a) Write a C program that uses Stack operations to Convert infix expression into postfix expression

Algorithm to Transform Infix Expression into Postfix Expression using Stack Transform ( ):

Description: Here I is an arithmetic expression written in infix notation and P is the equivalent postfix expression generated by this algorithm.

Algorithm.

1. Push “(“ left parenthesis onto stack.

2. Add “)” right parenthesis to the end of expression I.

3. Scan I from left to right and repeat step 4 for each element of I a. until the stack becomes empty.

4. If the scanned element is:

(i) an operand then add it to P.

(ii) a left parenthesis then push it onto stack. (iii) an operator then:

(iv) Pop from stack and add to P each operator (v) which has the same or higher precedence then (vi) the scanned operator.

(vii) (ii) Add newly scanned operator to stack. (viii) a right parenthesis then:

b. Pop from stack and add to P each operator

(i) until a left parenthesis is encountered. c. Remove the left parenthesis.

(i) [End of Step 4 If]

(ii) [End of step 3 For Loop] 5. Exit.

(30)

P a g e | 30 Department of Computer Science & Engineering GEC

Algorithm to Evaluate Postfix Expression using Stack Evaluate ( ):

Description: Here P is a postfix expression and this algorithm evaluates it.

1) Add a “)” right parenthesis at the end of P.

2) Scan P from left to right and repeat steps 3 & 4 for each element i) of P until “)” is encountered.

3) If an operand is encountered, push it onto stack. 4) If an operator ? is encountered then:

i) Pop the top two elements from stack, where A is the ii) top element and B is the next to top element.

iii) Evaluate B ? A.

iv) Place the result of (b) back on stack. v) [End of Step 4 If]

vi) [End of step 2 For Loop]

5) Set VALUE equal to the top element on the stack. 6) Exit.

(31)

P a g e | 31 Department of Computer Science & Engineering GEC

b). Write C programs that implement Queue (its operations) using arrays. Algorithm to Insert Item into Queue

Insert ( ):

Description: Here QUEUE is an array with N locations. FRONT and REAR points to the front and rear of the QUEUE. ITEM is the value to be inserted.

1. If (REAR == N) Then [Check for overflow] 2. Print: Overflow

3. Else

4. If (FRONT and REAR == 0) Then [Check if QUEUE is empty] (a) Set FRONT = 1

(b) Set REAR = 1 5. Else

6. Set REAR = REAR + 1 [Increment REAR by 1] [End of Step 4 If]

7. QUEUE[REAR] = ITEM 8. Print: ITEM inserted

[End of Step 1 If] 9. Exit

Algorithm to Delete Item from Queue Delete ( ):

Description: Here QUEUE is an array with N locations. FRONT and REAR points to the front and rear of the QUEUE.

1. If (FRONT == 0) Then [Check for underflow] 2. Print: Underflow

3. Else

4. ITEM = QUEUE[FRONT]

5. If (FRONT == REAR) Then [Check if only one element is left] (a) Set FRONT = 0

(32)

P a g e | 32 Department of Computer Science & Engineering GEC

6. Else

7. Set FRONT = FRONT + 1 [Increment FRONT by 1] [End of Step 5 If]

8. Print: ITEM deleted [End of Step 1 If] 9. Exit

(33)

P a g e | 33 Department of Computer Science & Engineering GEC

c).Write C programs that implement Queue (its operations) using linked lists /*Queue Using Linked List*/

ALGORITHM:

Algorithm to Insert Item into Queue Insert ( ):

Description: Here QUEUE is an array with N locations. FRONT and REAR points to the front and rear of the QUEUE. ITEM is the value to be inserted.

1. If (REAR == N) Then [Check for overflow] 2. Print: Overflow

3. Else

4. If (FRONT and REAR == 0) Then [Check if QUEUE is empty] (a) Set FRONT = 1

(b) Set REAR = 1 5. Else

6. Set REAR = REAR + 1 [Increment REAR by 1] [End of Step 4 If]

7. QUEUE[REAR] = ITEM 8. Print: ITEM inserted [End of Step 1 If] 9. Exit

Algorithm to Delete Item from Queue Delete ( ):

Description: Here QUEUE is an array with N locations. FRONT and REAR points to the front and rear of the QUEUE.

1. If (FRONT == 0) Then [Check for underflow] 2. Print: Underflow

3. Else

4. ITEM = QUEUE[FRONT]

(34)

P a g e | 34 Department of Computer Science & Engineering GEC

(a) Set FRONT = 0 (b) Set REAR = 0 6. Else

7. Set FRONT = FRONT + 1 [Increment FRONT by 1] [End of Step 5 If]

8. Print: ITEM deleted [End of Step 1 If] 9. Exit

Algorithm to Insert Item into Circular Queue Insert Circular ( ):

Description: Here QUEUE is an array with N locations. FRONT and REAR points to the front and rear elements of the QUEUE. ITEM is the value to be inserted.

1. If (FRONT == 1 and REAR == N) or (FRONT == REAR + 1) Then 2. Print: Overflow

3. Else

4. If (REAR == 0) Then [Check if QUEUE is empty] (a) Set FRONT = 1

(b) Set REAR = 1

5. Else If (REAR == N) Then [If REAR reaches end if QUEUE] 6. Set REAR = 1

7. Else

8. Set REAR = REAR + 1 [Increment REAR by 1] [End of Step 4 If]

9. Set QUEUE[REAR] = ITEM 10. Print: ITEM inserted

[End of Step 1 If] 11. Exit

(35)

P a g e | 35 Department of Computer Science & Engineering GEC

Exercise 8:

a) Write a C program that uses functions to create a Singly linked list

ALGORITHM:

Description: Here START is a pointer variable which contains the address of first node. PTR will point to the current node and PREV will point to the previous node. REV will maintain the reverse list.

1. Set PTR = START, PREV = NULL 2. Repeat While (PTR!= NULL) 3. REV = PREV

4. PREV = PTR 5. PTR = PTR->LINK 6. PREV->LINK = REV [End of While Loop] 7. START = PREV 8. Exit

ALGORITHM TO INSERT ITEM AFTER A SPECIFIC NODE

INSERT SPECIFIC ( ):

Description: Here START is a pointer variable which contains the address of first node. NEW is a pointer

variable which will contain address of new node. N is the value after which new node is to be inserted and

ITEM is the value to be inserted. 1. If (START == NULL) Then

2. Print: Linked-List is empty. It must have at least one node 3. Else

4. Set PTR = START, NEW = START 5. Repeat While (PTR != NULL)

(36)

P a g e | 36 Department of Computer Science & Engineering GEC

6. If (PTR->INFO == N) Then 7. NEW = New Node

8. NEW->INFO = ITEM 9. NEW->LINK = PTR->LINK 10. PTR->LINK = NEW 11. Print: ITEM inserted 12. ELSE

(37)

P a g e | 37 Department of Computer Science & Engineering GEC

b) Write a C program that uses functions to perform insertion operation on a Singly linked list

ALGORITHM:

INSERTED ( ):

Description: Here START is a pointer variable which contains the address of first

node. PREV is a pointer variable which contains address of previous node. ITEM is the value to be inserted.

1. If (START == NULL) Then [Check whether list is empty] 2. START = New Node [Create a new node]

3. START->INFO = ITEM [Assign ITEM to INFO field] 4. START->LINK = NULL [Assign NULL to LINK field] 5. Else

6. If (ITEM < START->INFO) Then [Check whether ITEM is less then value in first node]

7. PTR = START 8. START = New Node 9. START->INFO = ITEM 10. START->LINK = PTR 11. Else

12. Set PTR = START, PREV = START 13. Repeat While (PTR != NULL) 14. If (ITEM < PTR->INFO) Then 15. PREV->LINK = New Node 16. PREV = PREV->LINK 17. PREV->INFO = ITEM 18. PREV->LINK = PTR 19. Return

20. Else If (PTR->LINK == NULL) Then [Check whether PTR reaches last node]

(38)

P a g e | 38 Department of Computer Science & Engineering GEC 22. PTR = PTR->LINK 23. PTR->INFO = ITEM 24. PTR->LINK = NULL 25. Return 26. Else 27. PREV = PTR 28. PTR = PTR->LINK [End of Step 14 If] [End of While Loop] [End of Step 6 If] [End of Step 1 If] 29. Exit

(39)

P a g e | 39 Department of Computer Science & Engineering GEC

c) Write a C program that uses functions to perform deletion operation on a Singly linked list

ALGORITHM:

DELETE LAST ( ):

Description: Here START is a pointer variable which contains the address of first

node. PTR is a pointer variable which contains address of node to be deleted. PREV is a pointer variable which points to previous node. ITEM is the value to be deleted.

1. If (START == NULL) Then [Check whether list is empty] 2. Print: Linked-List is empty.

3. Else

4. PTR = START, PREV = START 5. Repeat While (PTR->LINK != NULL) 6. PREV = PTR [Assign PTR to PREV]

7. PTR = PTR->LINK [Move PTR to next node] [End of While Loop]

8. ITEM = PTR->INFO [Assign INFO of last node to ITEM] 9. If (START->LINK == NULL) Then [If only one node is left] 10. START = NULL [Assign NULL to START]

11. Else

9. PREV->LINK = NULL [Assign NULL to link field of second last node] [End of Step 9 If]

10. Delete PTR

11. Print: ITEM deleted [End of Step 1 If] 12. Exit

(40)

P a g e | 40 Department of Computer Science & Engineering GEC

Exercise 9:

d) Adding two large integers which are represented in linked list fashion.

ALGORITHM:

ADD ( ):

Description: Here A is a two – dimensional array with M rows and N columns and B is a two –dimensional array with X rows and Y columns. This algorithm adds these two arrays.

1. If (M ? X) or (N ? Y) Then 2. Print: Addition is not possible. 3. Exit

[End of If]

4. Repeat For I = 1 to M 5. Repeat For J = 1 to N

6. Set C[I][J] = A[I][J] + B[I][J] [End of Step 5 For Loop] [End of Step 6 For Loop] 7. Exit

Explanation: First, we have to check whether the rows of array A are equal to the rows of array B or the columns of array A are equal to the columns of array B. if they are not equal, then addition is not possible and the algorithm exits. But if they are equal, then first for loop iterates to the total number of rows i.e. M

and the second for loop iterates to the total number of columns i.e. N. In step 6, the element A[I][J] is added to the element B[I][J] and is stored in C[I][J] by the statement:

(41)

P a g e | 41 Department of Computer Science & Engineering GEC

e) Write a C program to reverse elements of a Single linked list.

ALGORITHM:

Algorithm to Reverse a Linked List Reverse ( ):

Description: Here START is a pointer variable which contains the address of first node. PTR will point to the current node and PREV will point to the previous node. REV will maintain the reverse list.

1. Set PTR = START, PREV = NULL 2. Repeat While (PTR != NULL) 3. REV = PREV

4. PREV = PTR 5. PTR = PTR->LINK 6. PREV->LINK = REV [End of While Loop] 7. START = PREV 8. Exit

(42)

P a g e | 42 Department of Computer Science & Engineering GEC

f) Write a C program to representation the given Sparse matrix using arrays.

ALGORITHM:

Description: Here A is a two – dimensional array with M rows and N columns and B is a two – dimensional array with X rows and Y columns. This algorithm adds these two arrays.

1. If (M ? X) or (N ? Y) Then 2. Print: Addition is not possible. 3. Exit

[End of If]

4. Repeat For I = 1 to M 5. Repeat For J = 1 to N

6. Set C[I][J] = A[I][J] + B[I][J] [End of Step 5 For Loop] [End of Step 6 For Loop] 7. Exit

Explanation: First, we have to check whether the rows of array A are equal to the rows of array B or the

columns of array A are equal to the columns of array B. if they are not equal, then addition is not possible

and the algorithm exits. But if they are equal, then first for loop iterates to the total number of rows i.e. M

and the second for loop iterates to the total number of columns i.e. N. In step 6, the element A[I][J] is

added to the element B[I][J] and is stored in C[I][J] by the statement: C[I][J] = A[I][J] + B[I][J

(43)

P a g e | 43 Department of Computer Science & Engineering GEC

g) Write a C program to representation the given Sparse matrix using linked list

ALGORITHM:

Description: Here A is a two – dimensional array with M rows and N columns and B is a two – dimensional array with X rows and Y columns. This algorithm multiplies these two arrays.

1. If (M ? Y) or (N ? X) Then

2. Print: Multiplication is not possible. 3. Else

4. Repeat For I = 1 to N 5. Repeat For J = 1 to X 6. Set C[I][J] = 0

7. Repeat For K = 1 to Y

8. Set C[I][J] = C[I][J] + A[I][K] * B[K][J] [End of Step 7 For Loop]

[End of Step 5 For Loop] [End of Step 4 For Loop] [End of If]

9. Exit

Explanation: First we check whether the rows of A are equal to columns of B or the columns of A are

equal to rows of B. If they are not equal, then multiplication is not possible. But, if they are equal, the first

for loop iterates to total number of columns of A i.e. N and the second for loop iterates to the total number

of rows of B i.e. X. In step 6, all the elements of C are set to zero. Then the third for loop iterates to total

number of columns of B i.e. Y. In step 8, the element A[I][K] is multiplied with B[K][J] and added to

C[I][J] and the result is assigned to C[I][J] by the statement: C[I][J] = C[I][J] + A[I][K] * B[K][J

(44)

P a g e | 44 Department of Computer Science & Engineering GEC

Exercise10:

a) Write a C program to Create a Binary Tree of integers

ALGORITHM:

Binary tree is an important type of structure which occurs very often. It is

characterized by the fact that any node can have at most two branches, i.e.,there is no node with degree greater than two. For binary trees we distinguish between the subtree on the left and on the right, whereas for trees the order of the subtree was irrelevant. Also a binary tree may have zero nodes. Thus a binary tree is really a different object than a tree.

Definition: A binary tree is a finite set of nodes which is either empty or consists of a root and two disjoint binary trees called the left subtree and the right subtree.

We can define the data structure binary tree as follows: structure BTREE

declare CREATE( ) --> btree

ISMTBT(btree,item,btree) --> boolean MAKEBT(btree,item,btree) --> btree LCHILD(btree) --> btree

DATA(btree) --> item RCHILD(btree) --> btree for all p,r in btree, d in item let ISMTBT(CREATE)::=true ISMTBT(MAKEBT(p,d,r))::=false LCHILD(MAKEBT(p,d,r))::=p; LCHILD(CREATE)::=error DATA(MAKEBT(p,d,r))::d; DATA(CREATE)::=error RCHILD(MAKEBT(p,d,r))::=r; RCHILD(CREATE)::=error end end BTREE

(45)

P a g e | 45 Department of Computer Science & Engineering GEC

b) Write a recursive C program, for Traversing a binary tree in preorder, inorder and postorder.

ALGORITHM:

PREORDER

The first type of traversal is pre-order whose code looks like the following: sub P(TreeNode)

Output(TreeNode.value)

If LeftPointer(TreeNode) != NULL Then P(TreeNode.LeftNode)

If RightPointer(TreeNode) != NULL Then P(TreeNode.RightNode)

end sub

This can be summed up as

Visit the root node (generally output this) Traverse to left subtree

Traverse to right subtree

And outputs the following: F, B, A, D, C, E, G, I, H

IN-ORDER

The second(middle) type of traversal is in-order whose code looks like the following: sub P(TreeNode)

If LeftPointer(TreeNode) != NULL Then P(TreeNode.LeftNode)

Output(TreeNode.value)

If RightPointer(TreeNode) != NULL Then P(TreeNode.RightNode)

(46)

P a g e | 46 Department of Computer Science & Engineering GEC

This can be summed up as

Traverse to left subtree

Visit root node (generally output this) Traverse to right subtree

And outputs the following: A, B, C, D, E, F, G, H, I POST-ORDER

The last type of traversal is post-order whose code looks like the following: sub P(TreeNode)

If LeftPointer(TreeNode) != NULL Then P(TreeNode.LeftNode)

If RightPointer(TreeNode) != NULL Then P(TreeNode.RightNode)

Output(TreeNode.value) end sub

This can be summed up as

Traverse to left subtree Traverse to right subtree

Visit root node (generally output this)

(47)

P a g e | 47 Department of Computer Science & Engineering GEC

Exercise 11:

a) Write a C program to Create a BST Algorithm CreateBST (A)

Create a binary search tree (BST) from an array A with N elements. root the root of a new binary search tree named T;

index 1;

while index N do

InsertBST (A[index ], root); index index + 1;

end while return T

Algorithm InOrder (root)

Perform an inorder (second-visit) traversal of the BST with root named root. if root is empty then

return else

InOrder (left child of root); output the value in root; InOrder (right child of root); end if

Algorithm TreeSort (A)

Sort the elements in array A using a binary search tree (BST).

CreateBST (A); {Creates a new BST T containing the elements of A} InOrder (root of T); {Sorts the elements in T using an inorder traversal}

b) Write a C program to insert a note into a BST. Binary Search Tree Algorithms

Algorithm Insert BST (v, root)

(48)

P a g e | 48 Department of Computer Science & Engineering GEC

if root is empty then root v;

else

node root;

loop {an infinite loop; we will explicitly exit the loop after v is inserted} if v value stored in node then

if the left child of node exists then node left child of node;

else

insert v as the left child of node; exit the loop;

end if else

if the right child of node exists then node right child of node;

else

insert v as the right child of node; exit the loop;

end if end if end loop end if

Algorithm InsertBST (v, root)

Recursively insert a value v into a binary search tree (BST) with root named root. if root is empty then

root v; else

if v value stored in root then if the left child of root exists then InsertBST (v, left child of root); else

(49)

P a g e | 49 Department of Computer Science & Engineering GEC

end if else

if the right child of root exists then InsertBST (v, right child of root); else

insert v as the right child of root; end if

end if end if

c) Write a C program to delete a note from a BST. DELETION ALGORITHM

1) Check for the cases that the delete operation fails: a. IF <root> == NULL (tree is empty)

b. Search the BST for the element to be deleted; IF <element> is not found (there is no such element in the tree).

// In both cases a&b the delete operation fails.

2) IF <element> is found, then the delete operation has four cases:

case 1: The <node> to be deleted has no <left> and <right> subtrees; that is, the <node> to be deleted is a leaf. // the easiest case

case 2: The <node> to be deleted has no <left> subtree; that is, the <left> subtree is empty. but it has nonempty <right> subtree.

case 3: The <node> to be deleted has no <right> subtree; that is, the <right> subtree is empty. but it has nonempty <left> subtree.

case 4: The <node> to be deleted has nonempty <left> and <right> subtrees; that is, the <node> to be deleted has <left> and <right> subtrees. // the hardest case

(50)

P a g e | 50 Department of Computer Science & Engineering GEC

Exercise 12:

a) Write a C program to compute the shortest path of a graph using Dijkstra’s algorithm

To implement Dijkstra’s Algorithm DESCRIPTION:

Shortest path from a specified vertex „S‟ to another specified vertex „T‟ can be stated as follows:

A simple weighted Graph „G‟of n vertices is described by a n*n matrix D = [d ij]

Where d ij=length (or distance or weight) of the directed edge from vertex

i to vertex j, d ij >=0

D ij=0

D ij=∞, if there is no edge from I to j

(In the problem ∞ is replaced with some large number 99999) The distance of a directed path „p‟ is defined to be the

„S‟ denotes the Starting vertex „T‟ denotes the Terminal vertex

(51)

P a g e | 51 Department of Computer Science & Engineering GEC

EXAMPLE:

Finding the shortest path from vertex „B‟ to G:

 Starting vertex B is labeled 0.  All successor of B get labeled.  Smallest label become permanent  Successor of „C‟ gets labeled.

A B C D E F G ∞ 0 ∞ ∞ ∞ ∞ ∞ 7 0 1 ∞ ∞ ∞ ∞ 7 0 1 ∞ ∞ ∞ ∞ 4 0 1 ∞ 5 4 ∞ 4 0 1 ∞ 5 4 ∞ 4 0 1 14 5 4 11 4 0 1 14 5 4 11 4 0 1 12 5 4 11 4 0 1 12 5 4 7 4 0 1 12 5 4 7 Destination vertex gets permanently labeled.

(52)

P a g e | 52 Department of Computer Science & Engineering GEC

b) Write a C program to find the minimum spanning tree using Warshall’s Algorithm

ALGORITHM:

Warshall algorithm is a dynamic programming formulation, to solve the all-pairs shortest path problem on directed graphs. It finds shortest path between all nodes in a graph. If finds only the lengths not the path. The algorithm considers the intermediate vertices of a simple path are any vertex present in that path other than the first and last vertex of that path.

Algorithm:

Input Format: Graph is directed and weighted. First two integers must be number of vertices and edges which must be followed by pairs of vertices which has an edge between them.

maxVertices represents maximum number of vertices that can be present in the graph. vertices represent number of vertices and edges represent number of edges in

thegraph.

graph[i][j] represent the weight of edge joining i and j.

size[maxVertices] is initialed to{0}, represents the size of every vertex i.e. the number of edges corresponding to the vertex.

visited[maxVertices]={0} represents the vertex that have been visited.

distance[maxVertices][maxVertices] represents the weight of the edge between the two vertices or distance between two vertices.

Initialize the distance between two vertices using init() function. init() function- It takes the distance matrix as an argument. For iter=0 to maxVertices – 1

For jter=0 to maxVertices – 1 if(iter == jter)

distance[iter][jter] = 0 //Distance between two same vertices is 0 else

distance[iter][jter] = INF//Distance between different vertices is INF jter + 1

(53)

P a g e | 53 Department of Computer Science & Engineering GEC

iter + 1

Where, INF is a very large integer value. Initialize and input the graph.

Call Floyd Warshall function.

• It takes the distance matrix (distance[maxVertices][maxVertices]) and number of vertices as argument (vertices).

• Initialize integer type from, to, via For from=0 to vertices-1

For to=0 to vertices-1 For via=0 to vertices-1

distance[from][to] = min(distance[from][to],distance[from] [via]+distance[via][to])

via + 1 to + 1

from + 1

This finds the minimum distance from from vertex to to vertex using the min function. It checks it there are intermediate vertices between the from and to vertex that form the shortest path between them

• min function returns the minimum of the two integers it takes as argument. Output the distance between every two vertices.

(54)

P a g e | 54 Department of Computer Science & Engineering GEC

ADD ON PROGRAMS :

1. Write a C program on Circular Queue operations

Circular Queue

A circular queue is a Queue but a particular implementation of a queue. It is very efficient. It is also quite useful in low level code, because insertion and deletion are totally independant, which means that you don't have to worry about an interrupt handler trying to do an insertion at the same time as your main code is doing a deletion.

Algorithm for Insertion:-

Step-1: If "rear" of the queue is pointing to the last position then go to step-2 or else step-3 Step-2: make the "rear" value as 0

Step-3: increment the "rear" value by one Step-4:

1. if the "front" points where "rear" is pointing and the queue holds a not NULL value for it, then its a "queue overflow" state, so quit; else go to step-4.2

2. insert the new value for the queue position pointed by the "rear" Algorithm for deletion:-

Step-1: If the queue is empty then say "empty queue" and quit; else continue Step-2: Delete the "front" element

Step-3: If the "front" is pointing to the last position of the queue then step-4 else step-5 Step-4: Make the "front" point to the first position in the queue and quit

(55)

P a g e | 55 Department of Computer Science & Engineering GEC

2. Write a C program on Evaluation on Postfix Expression

Postfix Evaluation

Infix Expression :

Any expression in the standard form like "2*3-4/5" is an Infix(Inorder) expression.

Postfix Expression :

The Postfix(Postorder) form of the above expression is "23*45/-".

Postfix Evaluation :

In normal algebra we use the infix notation like a+b*c. The corresponding postfix notation is abc*+. The algorithm for the conversion is as follows :

 Scan the Postfix string from left to right.  Initialise an empty stack.

 If the scannned character is an operand, add it to the stack. If the scanned character is an operator, there will be atleast two operands in the stack.

 If the scanned character is an Operator, then we store the top most element of the stack(topStack) in a variable temp. Pop the stack. Now evaluate topStack(Operator)temp. Let the result of this operation be retVal. Pop the stack and Push retVal into the stack.

Repeat this step till all the characters are scanned.

 After all characters are scanned, we will have only one element in the stack. Return topStack.

Example :

Let us see how the above algorithm will be imlemented using an example. Postfix String : 123*+4-

Initially the Stack is empty. Now, the first three characters scanned are 1,2 and 3, which are operands. Thus they will be pushed into the stack in that order.

Stack

Expression

Next character scanned is "*", which is an operator. Thus, we pop the top two elements from the stack and perform the "*" operation with the two operands. The second

(56)

P a g e | 56 Department of Computer Science & Engineering GEC Stack

Expression

The value of the expression(2*3) that has been evaluated(6) is pushed into the stack.

Stack

Expression

Next character scanned is "+", which is an operator. Thus, we pop the top two elements from the stack and perform the "+" operation with the two operands. The second

operand will be the first element that is popped.

Stack

Expression

The value of the expression(1+6) that has been evaluated(7) is pushed into the stack.

Stack

Expression

Next character scanned is "4", which is added to the stack.

Stack

Expression

Next character scanned is "-", which is an operator. Thus, we pop the top two elements from the stack and perform the "-" operation with the two operands. The second operand will be the first element that is popped.

(57)

P a g e | 57 Department of Computer Science & Engineering GEC Stack

Expression

The value of the expression(7-4) that has been evaluated(3) is pushed into the stack.

Stack

Expression

Now, since all the characters are scanned, the remaining element in the stack (there will be only one element in the stack) will be returned.

End result :

Postfix String : 123*+4- Result : 3

(58)

P a g e | 58 Department of Computer Science & Engineering GEC

3. Write a C program search the elements using Breadth First Search Algorithm & Depth First Search Algorithm

DESCRIPTION:

1. A graph can be thought of a collection of vertices (V) and edges (E), so we write, G = (V, E)

2. Graphs can be directed, or undirected, weighted or unweighted.

3. A directed graph, or digraph, is a graph where the edge set is an ordered pair. That is, edge 1 being connected to edge 2 does not imply that edge 2 is connected to edge 1. (i.e. it has direction – trees are special kinds of directed graphs).

4. An undirected graph is a graph where the edge set in an unordered pair. That is, edge 1 being connected to edge 2 does imply that edge 2 is connected to edge 1.

5. A weighted graph is graph which has a value associated with each edge. This can be a distance, or cost, or some other numeric value associated with the edge.

ALGORITHM FOR DEPTH FIRST SEARCH AND TRAVERSAL:

A depth first search of a graph differs from a breadth first search in that the exploration of a vertex v is suspended as soon as a new vertex is reached. At this time of exploration of the new vertex u begins. When this new vertex has been explored, the exploration of v continues. The search terminates when all reached vertices have been fully explored. The search process is best described recursively in the following algorithm.

Algorithm DFS(v)

// Given an undirected(directed) graph G=(V,E) with n vertices and an

//array visited [] initially set to zero, this algorithm visits all vertices reachable //from v. G and visited[] are global.

{

visited[v]:=1;

for each vertex w adjacent from v do {

if (visited[w]=0) then DFS(w);

(59)

P a g e | 59 Department of Computer Science & Engineering GEC

DESCRIPTION:

1. A graph can be thought of a collection of vertices (V) and edges (E), so we write, G = (V, E)

2. Graphs can be directed, or undirected, weighted or unweighted.

3. A directed graph, or digraph, is a graph where the edge set is an ordered pair. That is, edge 1 being connected to edge 2 does not imply that edge 2 is connected to edge 1. (i.e. it has direction – trees are special kinds of directed graphs).

4. An undirected graph is a graph where the edge set in an unordered pair. That is, edge 1 being connected to edge 2 does imply that edge 2 is connected to edge 1.

5. A weighted graph is graph which has a value associated with each edge. This can be a distance, or cost, or some other numeric value associated with the edge.

ALGORITHM FOR BREADTH FIRST SEARCH AND TRAVERSAL:

In Breadth first search we start at vertex v and mark it as having been reached (visited) the vertex v is at this time said to be unexplored. A vertex is said to have been explored by an algorithm when the algorithm has visited all vertices adjacent from it. All unvisited vertices adjacent from v are visited next. These are new unexplored vertices. Vertex v has now been explored. The newly visited vertices have not been explored and or put on to the end of a list of unexplored list of vertices. The first vertex on this list is the next to be explored.

Exploration continues until no unexplored vertex is left. The list of unexplored vertices operates as a queue and can be represented using any of the standard queue representations.

Algorithm BFS(v)

//A breadth first search of G is carried out beginning at vertex v. For //any node I, visited[I=1 if I has already been visited. The graph G //and array visited are global; visited[] is initialized to zero.

{

u:=v; //q is a queue of unexplored vertices visited[v]:=1;

repeat {

(60)

P a g e | 60 Department of Computer Science & Engineering GEC { if (visited[w]=0) then { add w to q; //w is unexplored visited[w]:=1; } }

if q is empty then return; //no unexplored vertex delete u from q; //get first unexplored vertex }until(false);

}

Algorithm BFT(G, n) //Breadth first traversal of G {

for I:=1 to n do //mark all vertices unvisited visited[I]:=0;

for I:=1 to n do if (visited[I]=0) then BFS(i);

(61)

P a g e | 61 Department of Computer Science & Engineering GEC

4. Write a C program to perform various operations i.e., insertions and deletions on AVL trees

AVL Trees: Also called as: Height Balanced Binary Search Trees. Search, Insertion, and Deletion can be implemented in worst case O (log n) time.

Definition: An AVL tree is a binary search tree in which

1. The heights of the right subtree and left subtree of the root differ by at most 1 2. The left subtree and the right subtree are themselves AVL trees

3. A node is said to be

left-high if the left subtree has

greater height /

right-high if the right subtree has greater height

equal if the heights of the LST and RST are the same -

(62)

P a g e | 62 Department of Computer Science & Engineering GEC

Figure 2: An AVL tree with height h

Maximum Height of an AVL Tree: What is the maximum height of an AVL tree having

exactly n nodes? To answer this question, we will pose the following question:

What is the minimum number of nodes (sparsest possible AVL tree) an

AVL tree of height h can have?

Let Fh be an AVL tree of height h, having the minimum number of nodes. Fh can be

visualized as in Figure 2.

Let Fl and Fr be AVL trees which are the left subtree and right subtree, respectively, of Fh.

Then Fl or Fr must have height h-2.

Suppose Fl has height h-1 so that Fr has height h-2. Note that Fr has to be an AVL tree having

the minimum number of nodes among all AVL trees with height of h-1. Similarly, Fr will

have the minimum number of nodes among all AVL trees of height h--2. Thus we have | Fh| = | Fh - 1| + | Fh - 2| + 1

Where | Fr| denotes the number of nodes in Fr. Such trees are called Fibonacci trees. See

(63)

P a g e | 63 Department of Computer Science & Engineering GEC

Figure 3: Fibonacci trees

Note that | F0| = 1 and | F1| = 2.

Adding 1 to both sides, we get

| Fh| + 1 = (| Fh - 1| + 1) + (| Fh - 2| + 1)

Thus the numbers | Fh| + 1 are Fibonacci numbers. Using the approximate formula for

Fibonacci numbers, we get

| F

h

| + 1

h 1.44log| Fn|

The sparsest possible AVL tree with n nodes has height

h 1.44log n The worst case height of an AVL tree with n nodes is 1.44log n

Algorithm for Insertions and Deletions into an AVL Trees:

While inserting a new node or deleting an existing node, the resulting tree may violate the (stringent) AVL property. To reinstate the AVL property, we use rotations. See Figure 4.

References

Related documents

The threshold into the stadium is through a series of layers which delaminate from the geometry of the field to the geometry of the city and creates zones of separation,

Marie Laure Suites (Self Catering) Self Catering 14 Mr. Richard Naya Mahe Belombre 2516591 [email protected] 61 Metcalfe Villas Self Catering 6 Ms Loulou Metcalfe

The corona radiata consists of one or more layers of follicular cells that surround the zona pellucida, the polar body, and the secondary oocyte.. The corona radiata is dispersed

The hypothesis for the second research question stated that students who participate in restorative justice practices experience a difference in Active Accountability compared to

As with other rapidly reconfigurable devices, optically reconfigurable gate arrays (ORGAs) have been developed, which combine a holographic memory and an optically programmable

While the pedestrian lane idea is not entirely original (examples of rear loading garages with front sidewalks that replace streets were built in Venice, California, as early as

How Many Breeding Females are Needed to Produce 40 Male Homozygotes per Week Using a Heterozygous Female x Heterozygous Male Breeding Scheme With 15% Non-Productive Breeders.

Despite the fact that the rise in net saving rate, capital stock and total consumption are the same in these two economies, the permanent increase in consumption that an