data structures lab programs

Upload: abirami-mani

Post on 14-Apr-2018

255 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/30/2019 data structures lab programs

    1/68

    II B.Tech Data Stractures

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

    INDEX

    S.No

    PROGRAMS LISTPageno

    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 ofintegers 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

  • 7/30/2019 data structures lab programs

    2/68

    II B.Tech Data Stractures

    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 usinglinked 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. 6612 a) Write a C program to compute the shortest path of a graph using

    Dijkstras algorithm

    67

    b) Write a C program to find the minimum spanning tree using Warshalls

    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 Algorithm108

    4

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

    111

  • 7/30/2019 data structures lab programs

    3/68

    II B.Tech Data Stractures

    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 NOTuse 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.

  • 7/30/2019 data structures lab programs

    4/68

    II B.Tech Data Stractures

    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.

  • 7/30/2019 data structures lab programs

    5/68

    II B.Tech Data Stractures

    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 isthe 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 condition1 ; 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)

  • 7/30/2019 data structures lab programs

    6/68

    II B.Tech Data Stractures

    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/30/2019 data structures lab programs

    7/68

    II B.Tech Data Stractures

    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 divisionalgorithm: 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 theremainder until we get a remainder 0. The last non-zero remainder is the gcd.

    This algorithm can be performed on a spreadsheet:

    A B C1 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 312 12 3 0

    13 3 0 #DIV/0!

    14 0 #DIV/0! #DIV/0!

    A B C1 m n

    2 1234563 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.

  • 7/30/2019 data structures lab programs

    8/68

    II B.Tech Data Stractures

    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 disksis 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 thesmaller one (see Fig. 3). At the end, disks should be in another

    arbitrary position.* )

    Fig. 3

    Solving the Tower of Hanoi

    http://wipos.p.lodz.pl/zylla/games/hanoi-ex.html#foot01#foot01http://wipos.p.lodz.pl/zylla/games/hanoi-ex.html#foot01#foot01http://wipos.p.lodz.pl/zylla/games/hanoi-ex.html#foot01#foot01http://wipos.p.lodz.pl/zylla/games/hanoi-ex.html#foot01#foot01
  • 7/30/2019 data structures lab programs

    9/68

    II B.Tech Data Stractures

    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 (N1)-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 4disk-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-hightower.

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

    Fig. 4

    From that position we have to move disk 4 from 'A' to 'C' andmove 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 2and 1 stacked on peg 'A'. So our goal now is to put disk 2 on

  • 7/30/2019 data structures lab programs

    10/68

    II B.Tech Data Stractures

    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 blueline), disks smaller than disk 2 stacked on peg 'B'. So, our goalnow is to put disk 1 on peg 'B'.

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

    Fig. 6

    So let's move it.

    Fig. 7

    The steps above are made by the algorithm implemented inTowers of Hanoiwhen one clicks the "Help me" button. Thisbutton-function makes analysis of the current position and

    generates only one single move which leads to the solution. Itis 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

    http://wipos.p.lodz.pl/zylla/games/hf.htmlhttp://wipos.p.lodz.pl/zylla/games/hf.htmlhttp://wipos.p.lodz.pl/zylla/games/hf.html
  • 7/30/2019 data structures lab programs

    11/68

    II B.Tech Data Stractures

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

    /*A

    recursive cprogramfortowersofhanoi: Ndisks

    aretobe

    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 thenone should use a kind ofback track programming, that is toremember previous steps of the analysis and not to repeat the

    analysis of the Towers from the ground.

  • 7/30/2019 data structures lab programs

    12/68

  • 7/30/2019 data structures lab programs

    13/68

    II B.Tech Data Stractures

    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 doesnt exist

    [End of If]

    7. Exit

  • 7/30/2019 data structures lab programs

    14/68

    II B.Tech Data Stractures

    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

  • 7/30/2019 data structures lab programs

    15/68

    II B.Tech Data Stractures

    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. Renumberremaining 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 theoriginal array with Fm-n numbers larger than the sought item and apply the above algorithm

    for n'=Fm.

  • 7/30/2019 data structures lab programs

    16/68

    II B.Tech Data Stractures

    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

    step4: reapeat step 1 to 3 until the list is sorted

  • 7/30/2019 data structures lab programs

    17/68

    II B.Tech Data Stractures

    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

    step5: combine the list

  • 7/30/2019 data structures lab programs

    18/68

    II B.Tech Data Stractures

    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.

  • 7/30/2019 data structures lab programs

    19/68

    II B.Tech Data Stractures

    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.

  • 7/30/2019 data structures lab programs

    20/68

    II B.Tech Data Stractures

    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;

    elsemaxchild = 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 checkfor 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){

    downHeap(a, i, array_size-1);

  • 7/30/2019 data structures lab programs

    21/68

    II B.Tech Data Stractures

    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 thesorted 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

  • 7/30/2019 data structures lab programs

    22/68

    II B.Tech Data Stractures

    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(n

    2) 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 toappend 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

    Content0 1

    81 - -644

    25 3616 - -

    949

    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

    01

    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 orradix.

    Generalized Radix Sorting:

  • 7/30/2019 data structures lab programs

    23/68

    II B.Tech Data Stractures

    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, egthe

    key is a date using the structure:

    typedef struct t_date {

    int day;

    int month;

    int year;

    } date;

    If the ranges forday and month are limited in the obvious way, and the range foryear

    is suitably constrained, eg1900 < year

  • 7/30/2019 data structures lab programs

    24/68

    II B.Tech Data Stractures

    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) orO(n). This result depends on k

    being constant.

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

    binary digits to represent an integer bk.

    However, if we need to have unique keys, then kmust 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!

  • 7/30/2019 data structures lab programs

    25/68

    II B.Tech Data Stractures

    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

  • 7/30/2019 data structures lab programs

    26/68

    II B.Tech Data Stractures

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

    11. If (I

  • 7/30/2019 data structures lab programs

    27/68

    II B.Tech Data Stractures

    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]

    7. Exit

  • 7/30/2019 data structures lab programs

    28/68

    II B.Tech Data Stractures

    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]

    7. Exit

  • 7/30/2019 data structures lab programs

    29/68

    II B.Tech Data Stractures

    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 intopostfix 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 Ia. 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.

  • 7/30/2019 data structures lab programs

    30/68

  • 7/30/2019 data structures lab programs

    31/68

    II B.Tech Data Stractures

    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

    (b) Set REAR = 0

  • 7/30/2019 data structures lab programs

    32/68

    II B.Tech Data Stractures

    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

  • 7/30/2019 data structures lab programs

    33/68

    II B.Tech Data Stractures

    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]

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

  • 7/30/2019 data structures lab programs

    34/68

    II B.Tech Data Stractures

    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

  • 7/30/2019 data structures lab programs

    35/68

    II B.Tech Data Stractures

    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)

  • 7/30/2019 data structures lab programs

    36/68

    II B.Tech Data Stractures

    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

    13. PTR = PTR->LINK

  • 7/30/2019 data structures lab programs

    37/68

    II B.Tech Data Stractures

    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 Singlylinked 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]21. PTR->LINK = New Node

  • 7/30/2019 data structures lab programs

    38/68

    II B.Tech Data Stractures

    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

  • 7/30/2019 data structures lab programs

    39/68

    II B.Tech Data Stractures

    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 Singlylinked 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

  • 7/30/2019 data structures lab programs

    40/68

    II B.Tech Data Stractures

    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 twodimensional array with M rows and N columns and B

    is a twodimensional 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, theelement 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

  • 7/30/2019 data structures lab programs

    41/68

    II B.Tech Data Stractures

    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

  • 7/30/2019 data structures lab programs

    42/68

    II B.Tech Data Stractures

    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 twodimensional array with M rows and N columns and B

    is a twodimensional 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] isadded 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

  • 7/30/2019 data structures lab programs

    43/68

    II B.Tech Data Stractures

    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 twodimensional array with M rows and N columns and B

    is a twodimensional 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

  • 7/30/2019 data structures lab programs

    44/68

    II B.Tech Data Stractures

    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 allp,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

  • 7/30/2019 data structures lab programs

    45/68

    II B.Tech Data Stractures

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

    b) Write a recursive C program, for Traversing a binary tree in preorder, inorderand 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 asVisit 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-ORDERThe 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)

    end sub

  • 7/30/2019 data structures lab programs

    46/68

    II B.Tech Data Stractures

    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)

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

  • 7/30/2019 data structures lab programs

    47/68

    II B.Tech Data Stractures

    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)

    Iteratively insert a value v into a binary search tree (BST) with root named root.

  • 7/30/2019 data structures lab programs

    48/68

    II B.Tech Data Stractures

    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

    insert v as the left child of root;

  • 7/30/2019 data structures lab programs

    49/68

    II B.Tech Data Stractures

    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 == NULL (tree is empty)b. Search the BST for the element to be deleted; IF is not found (there is no

    such element in the tree).// In both cases a&b the delete operation fails.

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

    case 1: The to be deleted has no and subtrees; that is, the

    to be deleted is a leaf. // the easiest case

    case 2: The to be deleted has no subtree; that is, the subtree is

    empty. but it has nonempty subtree.

    case 3: The to be deleted has no subtree; that is, the subtree is

    empty. but it has nonempty subtree.

    case 4: The to be deleted has nonempty and subtrees; that is,the to be deleted has and subtrees. // the hardest case

  • 7/30/2019 data structures lab programs

    50/68

    II B.Tech Data Stractures

    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 Dijkstrasalgorithm

    To implement Dijkstras Algorithm

    DESCRIPTION:

    Shortest path from a specified vertex S to another specified vertex T can be stated

    as follows:A simple weighted Graph Gof 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

    Disjkstras Alogrithm is the most efficient shortest path Alogrithm

  • 7/30/2019 data structures lab programs

    51/68

    II B.Tech Data Stractures

    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 114 0 1 14 5 4 11

    4 0 1 12 5 4 114 0 1 12 5 4 7

    4 0 1 12 5 4 7

    Destination vertex gets permanently labeled.

  • 7/30/2019 data structures lab programs

    52/68

    II B.Tech Data Stractures

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

    b) Write a C program to find the minimum spanning tree using WarshallsAlgorithm

    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 maxVertices1

    For jter=0 to maxVertices1

    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

  • 7/30/2019 data structures lab programs

    53/68

    II B.Tech Data Stractures

    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.

  • 7/30/2019 data structures lab programs

    54/68

    II B.Tech Data Stractures

    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. Itis 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 valuefor 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

    Step-5: Increment the "front" position by one

  • 7/30/2019 data structures lab programs

    55/68

    II B.Tech Data Stractures

    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 postfixnotation 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 mostelement 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 elementsfrom the stack and perform the "*" operation with the two operands. The second

    operand will be the first element that is popped.

  • 7/30/2019 data structures lab programs

    56/68

    II B.Tech Data Stractures

    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 elementsfrom the stack and perform the "+" operation with the two operands. The secondoperand 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 elementsfrom the stack and perform the "-" operation with the two operands. The second operand

    will be the first element that is popped.

  • 7/30/2019 data structures lab programs

    57/68

    II B.Tech Data Stractures

    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 willbe only one element in the stack) will be returned.

    End result :

    Postfix String : 123*+4-Result : 3

  • 7/30/2019 data structures lab programs

    58/68

    II B.Tech Data Stractures

    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 directiontrees are special kinds of directed graphs).

    4. An undirected graph is a graph where the edge set in an unordered pair. That is, edge 1being 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 adistance, 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);

    }

  • 7/30/2019 data structures lab programs

    59/68

    II B.Tech Data Stractures

    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 directiontrees are special kinds of directed graphs).

    4. An undirected graph is a graph where the edge set in an unordered pair. That is, edge 1being 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 adistance, 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

    {

    for all vertices w adjacent from u do

  • 7/30/2019 data structures lab programs

    60/68

    II B.Tech Data Stractures

    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);

    }

  • 7/30/2019 data structures lab programs

    61/68

    II B.Tech Data Stractures

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

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

    AVL Trees: Also called as: Height Balanced Binary Search Trees. Search, Insertion, andDeletion 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-highif the left subtree has

    greater height/

    right-highif the right subtree has

    greater height

    equalif the heights of the LST and

    RST are the same-

    Examples: Several examples of AVL trees are shown in Figure1.

  • 7/30/2019 data structures lab programs

    62/68

    II B.Tech Data Stractures

    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) anAVL tree of height h can have?

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

    visualized as in Figure 2.

    LetFl andFrbe AVL trees which are the left subtree and right subtree, respectively, ofFh.

    ThenFl orFrmust have height h-2.

    SupposeFl has height h-1 so thatFrhas height h-2. Note thatFrhas to be an AVL tree having

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

    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 inFr. Such trees are called Fibonacci trees. See

    Figure 3.

  • 7/30/2019 data structures lab programs

    63/68

    II B.Tech Data Stractures

    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

    |Fh| + 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 violatethe (stringent) AVL property. To reinstate the AVL property, we use rotations. See Figure 4.

  • 7/30/2019 data structures lab programs

    64/68

    II B.Tech Data Stractures

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

    Figure 4: Rotations in a binary search tree

    Rotation in a BST:

    Left rotation and right rotation can be realized by a three-way rotation of pointers.

    Left Rotation:

    Temp = p right ;

    p right = temp left ;

    temp left = p ;

    p = temp ;

    Left rotation and right rotation preserve

    BST property Inorder ordering of keys

    Problem Scenarios in AVL Tree Insertions left sub tree of node has degree higher by >= 2

    left child of node is left high (A) left child or node is right high (B)

    right sub tree has degree higher by >= 2 right child of node is left high (C) right child or node is right high (D)

    The AVL tree property may be violated at any node, not necessarily the root. Fixing

    the AVL property involves doing a series of single or double rotations.Double rotation involves a left rotation followed or preceded by a right rotation.

    In an AVL tree of height h, no more than [h/2] rotations are required to fix the AVL

    property.

  • 7/30/2019 data structures lab programs

    65/68

    II B.Tech Data Stractures

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

    Insertion: Problem Scenario 1: (Scenario D)Scenario A is symmetrical to the above. See Figure 5.

    Figure 5: Insertion in AVL trees: Scenario D

  • 7/30/2019 data structures lab programs

    66/68

    II B.Tech Data Stractures

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

    Insertion: Problem Scenario 2: (Scenario C)Scenario B is symmetrical to this. See Figure 6.

    Figure 6: Insertion in AVL trees: Scenario C

  • 7/30/2019 data structures lab programs

    67/68

    II B.Tech Data Stractures

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

    Deletion: Problem Scenario 1:

    Depending on the original height ofT2, the height of the tree will be either unchanged (height

    ofT2 = h) or gets reduced (if height ofT2 = h - 1). See Figure 7.

    Figure 7: Deletion in AVL trees: Scenario 1

    There is a scenario symmetric to this.

  • 7/30/2019 data structures lab programs

    68/68

    II B.Tech Data Stractures

    Deletion: Problem Scenario 2:See Figure 8. As usual, there is a symmetric scenario.

    Figure 8: Deletion in AVL trees: Scenario 2