Sie sind auf Seite 1von 15

UNIT 1

ARRAY:An array is a finite, ordered and collection of homogeneous data


clements. Array is finite because it contains only limited number of elements; and
ordered, as all the elements are stored one by one in contiguous locations of
computer memory in a linear ordered fashioe.
I. An array of integers to store the age of all students in a class.
2. An array of strings (of characters) to store the name of all villagers in a village.
MULTIDIMENSIONAL ARRAYS:
Two-dimensional Arrays:Two-dimensional arrays (alternatively termed as
matrices) are the collection of homogeneous
elements where the elements are ordered in a number of rows and columns. An
example of an m x n matrix where m denotes number of rows and n denotes
number of columns is as follows:
Memory representation of matrix: Like one-dimensional array, matrices are
also stored in contagious memory locations. There arc two conventions of storing
any matrix in memory: I. Row-major order 2. Column-major order. In row-major
order, elements of a matrix are stored on a row-by-row basis, that is, all the
clements in first row, then in second row and so on. On the other hand, in
column-major order. clements are stored column-by-column, that is, all the
clements in first column arc stored in their order of rows, then in

This matrix can be represented in memory as shown in Figure 2.9.

Row-major order. Assume that the base address is the first location of lhe
memory, that is, 1. So, the address of ay will be obtained as Address (a11) =
Storing all lhe elements in first (i - l )-lb rows + The number of elements in i-th
row up lo j-lh column.= (i - 1) x n + j So, for the matrix A3x•• lhe location of
al2 will be calculated as 10 (see Figure 2.9). Instead of considering lhe base
address to be 1, if it is at M, then the above formula can be easily
So, for the matrix A3x•• lhe location of al2 will be calculated as 10 (see Figure
2.9). Instead of considering lhe base address to be 1, if it is at M, then the
above formula can be easily modified as:Address (ai;l = M + (i - I) x n + j - 1
Column-major order. Let us first consider the starting location of matrix is
al memory location I. Then Address (aq) =Storing all the-elements in first (j -
1)-lb columns + The number of elements in j-th column up to i-th rows. = (j -
1) x m + i And considering 1he base address al M instead of I, the above
formula will stand as Address (aQ) = M + (j - 1) x m + i - I
Fibonacci search:The Fibonacci search technique is a method of searching a
sorted array using a divide and conquer algorithm that narrows down possible
locations with the aid of Fibonacci numbers. This method is faster than traditional
binary search algorithms, with a complexity of O(log(x)).
Algorithm:Let k be defined as an element in F, the array of Fibonacci numbers. n
= Fm is the array size. If the array size is not a Fibonacci number, let Fm be the
smallest number in F that is greater than n.The array of Fibonacci numbers is
defined where Fk+2 = Fk+1 + Fk, when k ≥ 0, F1 = 1, and F0 = 0. To test whether
an item is in the list of ordered numbers, follow these steps:
1. Set k = m.
2. If k = 0, stop. There is no match; the item is not in the array.
3. Compare the item against element in Fk-1.
4. If the item matches, stop.
5. If the item is less than entry Fk-1, discard the elements from positions Fk-1 +
1 to n. Set k = k - 1 and return to step 2.
6. If the item is greater than entry Fk-1, discard the elements from positions 1 to
Fk-1. Renumber the remaining elements from 1 to Fk-2, set k = k - 2, and
return to step 2.
Binary search:Algorithm : binary search Input : A, vector of n elements K,
search element Output :low –index of k Method : low=1,high=n
While(low<=high-1) { mid=(low+high)/2 if(k<a[mid]) high=mid else
low=mid if end } while end if(k=A[low]) { write("search successful")
write(k is at location low) exit(); } else write (search unsuccessful); if end;
algorithm ends.
Explain merge sort: As another example divide-and-conquer, we investigate a
sorting algorithm that has the nice property that is the worst case its complexity is
O(n log n) This algorithm is called merge sort
Algorithm For Merge Sort:Algorithm MergeSort(low,high)
//a[low:high] is a global array to be sorted //Small(P) is true if there is only one
element //to sort. In this case the list is already sorted. {
if (low<high) then //if there are more than one element { //Divide P into
subproblems //find where to split the set mid = [(low+high)/2]; //solve the
subproblems. mergesort (low,mid); mergesort(mid+1,high); //combine the solutions
.merge(low,mid,high); } }
Explain quick sort :In Quick sort, the division into 2 sub arrays is made so that the
sorted sub arrays do not need to be merged later.
Algorithm: Partition the array a[m:p-1] about a[m]
Algorithm Partition(a,m,p) //within a[m],a[m+1],…..,a[p-1] the elements
// are rearranged in such a manner that if //initially t=a[m],then after completion
//a[q]=t for some q between m and //p-1,a[k]<=t for m<=k<q, and //a[k]>=t for
q<k<p. q is returned //Set a[p]=infinite. {
v=a[m];I=m;j=p; repeat { repeat I=I+1; until(a[I]>=v); repeat j=j-1;
until(a[j]<=v); if (I<j) then interchange(a,i.j); } until(I>=j); a[m]=a[j]; a[j]=v; retun
j; }
Algorithm Interchange(a,I,j)://Exchange a[I] with a[j] { p=a[I];
a[I]=a[j]; a[j]=p; }
Algorithm: Sorting by Partitioning Algorithm Quicksort(p,q)
//Sort the elements a[p],….a[q] which resides //is the global array a[1:n] into
ascending //order; a[n+1] is considered to be defined // and must be >= all the
elements in a[1:n] { if(p<q) then // If there are more than one element { // divide p
into 2 subproblems j=partition(a,p,q+1);
//’j’ is the position of the partitioning element. //solve the subproblems.
quicksort(p,j-1); quicksort(j+1,q); //There is no need for combining solution. } }
UNIT 2
STACK: A stack is an ordered collection of items where new items may be
inserted or deleted only at one end, called the top of the stack.
A stack is a data structure that keeps objects in Last- In-First-Out (LIFO)
order, Objects are added to the top of the stack Only the top of the stack can be
accessed. Stacks have some useful terminology associated with them:
Push To add an element to the stack ,Pop To remove an element from the stock
Peek To look at elements in the stack without removing them LIFO Refers to the
last in, first out behavior of the stack .FILO Equivalent to LIFO
Implementation of stack: 1. Array (static memory) 2. linked list (dynamic
memory)
Operations of stack is 1. PUSH operations 2. POP operations 3. PEEK operations
The Stack ADT:A stack S is an abstract data type (ADT) supporting the following
three methods: push(n) : Inserts the item n at the top of stack
pop() : Removes the top element from the stack and returns that top element. An
error occurs if the stack is empty.
peek(): Returns the top element and an error occurs if the stack is empty.
PUSH:1. Adding an element into a stack (called PUSH operation)
Adding element into the TOP of the stack is called PUSH operation.
Check conditions : TOP = N , then STACK FULL where N is maximum size of the
stack. Adding into stack( PUSH algorithm ) procedure add(item :items);
{add item to the global stack stack ; top is the current top of stack and n is its
maximum size} begin if top = n then stackfull; top := top+1; stack(top) := item;
end:{of add}
POP:Deleting or Removing element from the TOP of the stack is called POP
operations. Check Condition: TOP = 0, then STACK EMPTY Deletion in stack (
POP Operation ) procedure delete(var item : items); {remove top element from
the stack stack and put it in the item} beginif top = 0 then
stackempty; item :=stack(top);top := top-1; end; {of delete}
Peek Operation::Returns the item at the top of the stack but does not delete it.This
can also result in underflow if the stack is empty.
Algorithm:PEEK(STACK, TOP) BEGIN /* Check, Stack is empty? */ if (TOP
== -1) then print “Underflow” and return 0. else item = STACK[TOP]
return item / * returns the top element to the user */ END
APPLICATIONS:
1. Expression evaluation
2. Backtracking (game playing, finding paths, exhaustive searching)
3. Memory management, run-time environment for nested language features.
HIERARCHY OF OPERATIONS:
The order in which the arithmetic operators are evaluated in an exp. is called
Hierarchy of operation. There are two levels of hierarchy of operations.
1. High priority operators.
Eg : ( ), Unary operator, Multiplication operator, % operator, / operator.
2. Low priority operators.
Eg: +, - . L = (6+5) * 3 – 25/5
Scan 1 : 11 * 3 - 25/5 Scan 2: 33 – 25/5 Scan 3: 33-5 Scan 4: 28.
During the scanning process the computer evaluate the operator based on priority. *
and / are same high level priority operator. + and – are same low level priority
operator.
Conversion of infix expression into postfix:
1. put the parenthesis in the given expression according to the priority of
operations.
2. now,every matched parenthesis have one operator . remove the operator and
place it after the
closed parenthesis and remove the parenthesis.
3. repeat step 2 ,no matched parenthesis occur in the given expression.
Eg:(A+(B*C)) (A+BC*) ABC*+
EVALUATION OF POSTFIX EXPRESSION USING STACK:
QUEUE:A queue is an ordered collection of items from which items may be
deleted at one end called the front and the items may be inserted at the other end
called rear of the queue.
PRINCIPLE:The first element inserted into a queue is the first element to be
removed. Queue is called First In First Out (FIFO) list.
BASIC OPERATIONS INVOLVED IN A QUEUE:
.Create a queue 2.Check whether a queue is empty or full 3.Add an item at the rear
end 4.Remove an item at front end 5.Read the front of the queue 6.Print the entire
queue
INSERTION OPERATION
An attempt to push an item onto a queue, when the queue is full, causes an
overflow..Check whether the queue is full before attempting to insert another
element. 2.Increment the rear pointer & 3. Insert the element at the rear pointer of
the queue.
ALGORITHM: Rear – Rear end pointer, Q – Queue, N – Total number of
elements & Item – The element to be inserted 1.if(Rear=N) [Overflow?] Then Call
QUEUE_FULL Return 2.Rear<-Rear+1 [Increment rear pointer] 3.Q[Rear]<-Item
[Insert element] End INSERT
DELETION OPERATION: An attempt to remove an element from the queue
when the queue is empty causes an underflow.
Deletion operation involves: 1.Check whether the queue is empty.
2.Increment the front pointer. 3.Remove the element.
ALGORITHM:Q – Queue , Front – Front end pointer , Rear – Rear end pointer &
Item – The element to be deleted. 1.if(Front=Rear) [Underflow?] Then Call
QUEUE_EMPTY 2. Front<-Front+1 [Incrementation] 3. Item<-Q [Front] [Delete
element] Thus queue is a dynamic structure that is constantly allowed to grow and
shrink and thus changes its size, when implemented using linked list.
PRIORITY QUEUES:They are a kind of queue in which the elements are
dequeued in priority order. A priority queue is a collection of elements where each
element has an associated priority. Elements are
added and removed from the list in a manner such that the element with the highest
(or lowest) priority is always the next to be removed. When using a heap
mechanism, a priority queue is quite efficient for this type of operation.
ALGORITHM: Priority Queue - Algorithms - Adjust
Adjust(i) left = 2i, right = 2i + 1 if left <= H.size and H[left] > H[i] then largest =
left else largest = i if right <= H.size and H[right] > H[largest] then largest =
right if largest != i then swap H[largest] with H[i] Adjust(largest)
Explanation:Adjust works recursively to guarantee the heap property. It compares
the current node with its children finding which, if either, has a greater priority. If
one of them does, it will swap array locations with the
largest child. Adjust is then run again on the current node in its new location.
Priority Queue - Algorithms - Insert Insert(Key) H.size = H.size + 1 i = H.size
while i > 1 and H[i/2] < Key H[i] = H[i/2] i =i/2 end while H[i] =key
xplanation:The insert algorithm works by first inserting the new element (key) at
the end of the array. This element is then compared with its parent for highest
priority. If the parent has a lower priority, the two elements are
swapped. This process is repeated until the new element has found its place.
Priority Queue - Algorithms - Extract Extract() Max = H[1]
H[1] = H[H.size] H.size = H.size - 1 Adjust(1) Return Max
Explanation:Extract works by removing and returning the first array element, the
one of highest priority, and then promoting the last array element to the first.
Adjust is then run on the first element so that the heap property is maintained.
QUEUES:Queue is an abstract data structure, somewhat similar to Stacks. Unlike
stacks, a queue is open at both its ends. One end is always used to insert data
(enqueue) and the other is used to remove data (dequeue). Queue follows
First-In-First-Out methodology, i.e., the data item stored first will be accessed first.
Types of Linked List:Following are the various flavours of linked list.
Simple Linked List − Item Navigation is forward only.
Doubly Linked List − Items can be navigated forward and backward way.
Circular Linked List − Last item contains link of the first element as next and and
first element has link to last element as prev.
Basic Operations:Following are the basic operations supported by a list.
Insertion − add an element at the beginning of the list. Deletion − delete an element
at the beginning of the list. Display − displaying complete list.
Search − search an element using given key. Delete − delete an element using given
key.
Insertion Operation:Insertion is a three step process − Create a new Link with
provided data.Point New Link to old First Link. Point First Link to this New
Link.
ALGORITHM://insert link at the first location void insertFirst(int key, int
data){ //create a link struct node *link = (struct node*) malloc(sizeof(struct
node)); link->key = key; link->data = data;
//point it to old first node link->next = head; //point first to new first
node head = link; }
Deletion Operation:Deletion is a two step process − Get the Link pointed by
First Link as Temp Link. Point First Link to Temp Link's Next Link.
//delete first item struct node* deleteFirst(){ //save reference to first link
struct node *tempLink = head; //mark next to first link as first
head = head->next; //return the deleted link return tempLink; }
CIRCULARLY LINKED LINEAR LIST:
In the singly linked linear list the last node consist of the NULL pointer. Slightly
improvement in this type of linked list is accomplished by replacing the null pointer
in the last node of a list with the address of its first node.such a list is called
circularly linked linear list or simply a circular list
ADVANTAGE OF CIRCULAR LIST OVER SINGLY LINKED LISTS:
1.Accessibility of a node from a given node, every node is easily accessible i.e., all
node be reached by merely chaining through the list
2. Deletion operation: In addition to the address of x the node to be deleted from a
singly list, it is also necessary to give address of the first node of the list in order to
the predecessor of X. Such a requirement does not exist for a circular list, since the
search for the predecessor of node X can be initiated from X itself.
DISADVANTAGE OF A CIRCULAR LIST:
In processing a circular list, if we are not able to detect the end of the list, it is
possible to get into an infinite loop. This problem can be sowed i.e, the end of list
can be detected by placing a special node which can be
easily identified in the circular list .This special node is often called the list head of
the circular list. One more advantage of using this technique is that the list can
never be empty which can be checked in the operation of singly linked list
UNIT 5
Jagged table: Jagged tables are nothing but the special kind of sparse matrices
such as triangular matrices, band matrices, etc…
 In the jagged tables, we put a restriction that in the row (or in a column) if
elements are present then they are contiguous.
 Thus in fig (a) - (e), all are jagged tables except the table in fig (f).
 The indexing formula can used to access the elements in the table.
 The indexing formula for any element aij in a matrix as Address (aij)= (i*(i-1))/2
+j
 We can access the row indices of the jagged table, such that, the ith entries in the
accss table is (i*(i-1)/2).
 The access table is calculated only at the time of initiation and a=can be stored in
memory, it can referred each time the access of element in the jagged table occur.
 We can also calculate by pure addition rather than multiplication or division such
as 0,1, (1+2), (1+2)+3,…
 For e.g., if we want to access a54 (element in 5th row and 4th column) then at
5th location of the access table, we see the entry is 10; hence desire element is at
14 (=10+4) location of the array which contains the elements. It is assumed that
the 1st element of the table is located at the location of the array.
 Above mentioned accessing technique has another advantage over the indexing
formula. We can find the indexing formula even if the jagged tables are asymmetric
with respect to the arrangement of elements in it.
Inverted tables:
 Suppose, a telephone company maintains records of all the subscribers of a
telephone exchange as shown in the fig given below.
These records can be used to serve several purposes.
 One of them requires the alphabetical ordering of name of the subscriber.
 Second, it requires the lexicographical ordering of the address of subscriber.
 Third, it also requires the ascending order of the telephone numbers in order to
estimate the cabling charge from the telephone exchange to the location of the
telephone connection etc...
 To serve these purposes, the telephone company should maintain 3 sets of
records: one in alphabetical order of the NAME, second, the lexicographical
ordering of the ADDRESS and third, the ascending order of the phone numbers.
 Some of the drawbacks are:
1. Requirement of extra storage: three times of the actual memory.
2. Difficult in modification of records: if a subscriber change his address then we
have to modify this in three storage otherwise consistency in information will be
lost.
 Using the concept of inverted tables, we can avid the multiple set of records, and
we can still retrieve the records by any of the three keys almost as quickly as if the
records are fully sorted by that key.
 Therefore, we should maintain an inverted table
SYMBOL TABLES-DEFINITION
A symbol table is a set of locations containing a record for each identifier with
fields for the attribute of the identifier. The attributes stored in a symbol
table are DATA TYPE: Numeric or Character SCOPE: Where the program is
valid ARGUMENT VALUES : The argument values that is used or returned in
the program An essential function of a compiler is to record the identifiers
and the related information about its attributes types
SYMBOL TABLES-REPRESENTATION

A typical symbol is represented as, 

Fig.: symbol table Where, X, Y, Z are the variables used in the program
I-COLUMN: It contains the entry of the variables
II-COLUMN: It contains the address where the value of these variables is stored.
SYMBOL TABLE - IMPLEMENTATION
The way to implement symbol tables are 
Static tree table - identifiers are known in advance and no. deletions or
insertions are allowed. 
Dynamic tree table - in which identifiers are not known in advance.
STATIC TREE TABLE:Symbol tables with property that, identifiers are known
in advance and no additions on deletions are performed are called static. One
solution is to sort the names and store them sequentially using binary search
tree. The implementation of static tree table is carried out by binary search
tree as follows,
DYNAMIC TREE TABLE:
The tree table in which identifiers are not known in advance and addition and
deletion are performed is a dynamic tree table.
Dynamic table may also be maintained as binary search trees. An identifier X may
be inserted into a binary search tree T by using the search algorithm to determine
the failure node corresponding to X. This gives the position in T where the
insertion is to be made
HASH TABLE:
The best search method, binary search technique involves number of comparisons,
which has a search time of O(log2n). Another approach is to compute the location
of the desired record. The nature of this computation depends on the key set and the
memory-space requirements of the desired record. This key-to-address
transformation problem is defined as a mapping or hashing function H, which maps
the key space (K) into an address space (A).
MID-SQUARE METHOD :A key is multiplied by itself and the address is
obtained by choosing an appropriate number of bits or digits from the middle of the
square. The selection of bits or digits based on the table size and also they should
fit into one computer word of memory.
E.g. Consider a key, 56789 and when it is squared we get 3224990521. If the three
digit address is needed, then positions 5 to 7 may chosen, giving address 990.
DIVISION METHOD :In this method, integer x is to divide by M and d then to
use the remainder modulo M. The hash function is H(x) = x mod M
Great care should be taken while choosing value for M and preferably it should be
an even number. By making M a large prime number the keys are spread out
evenly.
FOLDING METHOD :A key is partitioned into a number of parts, each of which
has the same length as the required address. The parts are then added together,
ignoring the final carry, to form an address. For eg., if the key 356942781 is to be
transformed into a three-digit address.
Two types:Fold-shifting: 356, 942 and 781 are added to yield 079. Fold-boundary
method: 653, 942 and 187 are added together, yielding 782.
Sequential Access –
It is the simplest access method. Information in the file is processed in order, one
record after the other. This mode of access is by far the most common; for example,
editor and compiler usually access the file in this fashion.Read and write make up
the bulk of the operation on a file. A read operation -read next- read the next
position of the file and automatically advance a file pointer, which keeps track I/O
location. Similarly, for the writewrite next append to the end of the file and
advance to the newly written material.
Key points:Data is accessed one record right after another record in an order.When
we use read command, it move ahead pointer by one
When we use write command, it will allocate memory and move the pointer to the
end of the file Such a method is reasonable for tape.
Direct Access –Another method is direct access method also known as relative
access method. A filed-length logical record that allows the program to read and
write record rapidly. in no particular order. The direct access is based on the disk
model of a file since disk allows random access to any file block. For direct access,
the file is viewed as a numbered sequence of block or record. Thus, we may read
block 14 then block 59 and then we can write block 17. There is no restriction on
the order of reading and writing for a direct access file.A block number provided by
the user to the operating system is normally a relative block number, the first
relative block of the file is 0 and then 1 and so on.
Index sequential method –
It is the other method of accessing a file which is built on the top of the direct
access method. These methods construct an index for the file. The index, like an
index in the back of a book, contains the pointer to the various blocks. To find a
record in the file, we first search the index and then by the help of pointer we
access the file directly.
Key points:It is built on top of Sequential access.It control the pointer by using
index.
UNIT 3
BINARY TREE TRAVERSALS
A binary tree traversal requires that each node of the tree be processed once and
only once in a predetermined sequence.
The two general approaches to the traversal sequence are,
Depth first traversal Breadth first traversal
In depth first traversal, the processing proceeds along a path from the root
through one child to the most distant descendent of that first child before
processing a second child. In other words, in the depth first traversal, all the
descendants of a child are processed before going to the next child.
In a breadth-first traversal, the processing proceeds horizontally form the root
to all its children, then to its children’s children, and so forth until all nodes
have been processed. In other words, in breadth traversal, each level is
completely processed before the next level is started.
Depth-First Traversal
There are basically three ways of binary tree traversals. They are :
Pre Order Traversal 2.In Order Traversal 3.Post Order Traversal
Steps : 1. Traverse left subtree in inorde ,Process root node 3.Traverse right
subtree in inorder Algorithm inoder traversal (Bin-Tree T) Begin If ( not
empty (T) ) then Begin Inorder_traversal ( left subtree ( T ) )Print ( info ( T )
)/ * process node */ Inorder_traversal ( right subtree ( T ) )End End
2. Preorder Traversal
Steps : 1. Process root node 2. Traverse left subtree in preorder 3.
Traverse right subtree in preorder
Algorithm
Algorithm preorder traversal (Bin-Tree T) Begin If ( not empty (T) ) then
Begin Print ( info ( T ) ) / * process node * / Preoder traversal (left subtree ( T )
) Inorder traversal ( right subtree ( T ) ) END END
3. Postorder Traversal
Steps : 1. Traverse left subtree in postorder 2.Traverse right subtree in
postorder 3.process root node
Algorithm
Postorder Traversal Algorithm postorder traversal (Bin-Tree T)
Begin If ( not empty (T) ) then Begin Postorder_traversal ( left subtree ( T ) )
Postorder_traversal ( right subtree( T)) Print ( Info ( T ) ) / * process node */
END END
BINARY SEARCH TREE:
Binary Search Tree is a node-based binary tree data structure which has the
following properties:
The left subtree of a node contains only nodes with keys lesser than the node’s
key. The right subtree of a node contains only nodes with keys greater than
the node’s key.
The left and right subtree each must also be a binary search tree.
ADVANTAGES;BST is fast in insertion and deletion etc when balanced. .Very
efficient and its code is easier than link lists. we can always keep the cost of
insert(), delete(), lookup() to O(logN) where N is the number of nodes in the tree -
so the benefit really is that lookups can be done in logarithmic time which matters a
lot when N is large.We have an ordering of keys stored in the tree. Any time we
need to traverse the increasing (or decreasing) order of keys, we just need to do the
in-order (and reverse in-order) traversal on the tree. We can implement order
statistics with binary search tree - Nth smallest, Nth largest element. This is
because it is possible to look at the data structure as a sorted array. We can also do
range queries - find keys between N and M (N <= M).
Disadvantages: Shape of the tree depends upon order of insertion and it can be
degenerated. Searching takes long time.
The main disadvantage is that we should always implement a balanced binary
search tree - AVL tree, Red-Black tree, Splay tree. Otherwise the cost of operations
may not be logarithmic and degenerate into a linear search on an array.
NEED FOR AVL TREE:
The purpose of the AVL tree is to avoid the poorly shaped trees and ensure that the
tree is always well balanced so that we are guaranteed of getting good search,
insert, and delete times. Suppose we build a tree (binary or AVL) by repeatedly
inserting n distinct items into an initially empty tree.
PROPERTIES:
Maximum possible number of nodes in AVL tree of height H = 2H+1 – 1
Minimum number of nodes in AVL Tree of height H is given by a recursive
relation- N(H) = N(H-1) + N(H-2) + 1
Minimum possible height of AVL Tree using N nodes= [log2N]
Maximum height of AVL Tree using N nodes is calculated using recursive relation-
N(H) = N(H-1) + N(H-2) + 1
TYPES OF REPRESENTING TREE:
Sequential Representation of Binary Tree.
Link Representation of Binary Tree.
1) Linked Representation of Binary Tree
Consider a Binary Tree T. T will be maintained in memory by means of a linked
list representation which uses three parallel arrays; INFO, LEFT, and RIGHT
pointer variable ROOT as follows. In Binary Tree each node N of T will
correspond to a location k such that LEFT [k] contains the location of the left child
of node N.
INFO [k] contains the data at the node N. RIGHT [k] contains the location of right
child of node N.
Representation of a node:

Example:Consider the binary tree T in the figure. A schematic diagram of the


linked list representation of T appears in the following figure. Observe that each
node is pictured with its three fields, and that the empty subtree is pictured by using
x for null entries.

Sequential representation of Binary Tree


Let us consider that we have a tree T. let our tree T is a binary tree that is complete
binary tree. Then there is an efficient way of representing T in the memory called
the sequential representation or array representation of T. This representation uses
only a linear array TREE as follows: The root N of T is stored in TREE [1]. If a
node occupies TREE [k] then its left child is stored in TREE [2 * k] and its right
child is stored into TREE [2 * k + 1].
For Example
B Tree:B Tree is a specialized m-way tree that can be widely used for disk access.
A B-Tree of order m can have at most m-1 keys and m children. One of the main
reason of using B tree is its capability to store large number of keys in a single node
and large key values by keeping the height of the tree relatively small. A B tree of
order m contains all the properties of an M way tree. In addition, it contains the
following properties Every node in a B-Tree contains at most m children. Every
node in a B-Tree except the root node and the leaf node contain at least m/2
children. The root nodes must have at least 2 nodes. All leaf nodes must be at the
same level.
It is not necessary that, all the nodes contain the same number of children but, each
node must have m/2 number of nodes.
A B tree of order 4 is shown in the following image.
INSERTION: Insertions are done at the leaf node level. The following algorithm
needs to be followed in order to insert an item into B Tree.
Traverse the B Tree in order to find the appropriate leaf node at which the node can
be inserted. If the leaf node contain less than m-1 keys then insert the element in
the increasing order. Else, if the leaf node contains m-1 keys, then follow the
following steps. Insert the new element in the increasing order of elements. Split
the node into the two nodes at the median. Push the median element upto its parent
node.
If the parent node also contain m-1 number of keys, then split it too by following
the same steps.
Deletion:Deletion is also performed at the leaf nodes. The node which is to be
deleted can either be a leaf node or an internal node. Following algorithm needs to
be followed in order to delete a node from a B tree. Locate the leaf node. If there
are more than m/2 keys in the leaf node then delete the desired key from the node.
If the leaf node doesn't contain m/2 keys then complete the keys by taking the
element from eight or left sibling. If the left sibling contains more than m/2
elements then push its largest element up to its parent and move the intervening
element down to the node where the key is deleted. If the right sibling contains
more than m/2 elements then push its smallest element up to the parent and move
intervening element down to the node where the key is deleted. If neither of the
sibling contain more than m/2 elements then create a new leaf node by joining two
leaf nodes and the intervening element of the parent node. If parent is left with less
than m/2 nodes then, apply the above process on the parent too. If the the node
which is to be deleted is an internal node, then replace the node with its in-order
successor or predecessor. Since, successor or predecessor will always be on the leaf
node hence, the process will be similar as the node is being deleted from the leaf
node.
Applications of binary trees:
Binary Search Tree - Used in many search applications where data is constantly
entering/leaving, such as the map and set objects in many languages' libraries.
Binary Space Partition - Used in almost every 3D video game to determine what
objects need to be rendered.
Binary Tries - Used in almost every high-bandwidth router for storing
router-tables.
Hash Trees - used in p2p programs and specialized image-signatures in which a
hash needs to be verified, but the whole file is not available.
Huffman Coding Tree (Chip Uni) - used in compression algorithms, such as
those used by the .jpeg and .mp3 file-formats.
GGM Trees - Used in cryptographic applications to generate a tree of
pseudo-random numbers.
Syntax Tree - Constructed by compilers and (implicitly) calculators to parse
expressions.
Treap - Randomized data structure used in wireless networking and memory
allocation.
T-tree - Though most databases use some form of B-tree to store data on the drive,
databases which keep all (most) their data in memory often use T-trees to do so.

unit 4
TOPOLOGICAL SORT:A topological ordering of a directed graph is a linear
ordering of its vertices such that for every directed edge uv from vertex u to vertex
v, u comes before v in the ordering —
Dijkstra’s algorithm :is very similar to Prim’s algorithm for minimum spanning
tree. Like Prim’s MST, we generate a SPT (shortest path tree) with given source as
root. We maintain two sets, one set contains vertices included in shortest path tree,
other set includes vertices not yet included in shortest path tree.
1) Create a set sptSet (shortest path tree set) that keeps track of vertices included in
shortest path tree, i.e., whose minimum distance from source is calculated and
finalized. Initially, this set is empty.
2) Assign a distance value to all vertices in the input graph. Initialize all distance
values as INFINITE. Assign distance value as 0 for the source vertex so that it is
picked first.
3) While sptSet doesn’t include all vertices….a) Pick a vertex u which is not there
in sptSet and has minimum distance value.….b) Include u to sptSet.
….c) Update distance value of all adjacent vertices of u. To update the distance
values, iterate through all adjacent vertices. For every adjacent vertex v, if sum of
distance value of u (from source) and weight of edge u-v, is less than the distance
value of v, then update the distance value of v.
GRAPH TRAVERSAL:
Breadth First Search or BFS for a Graph
Breadth First Traversal (or Search) for a graph is similar to Breadth First Traversal
of a tree (See method 2 of this post). The only catch here is, unlike trees, graphs
may contain cycles, so we may come to the same node again. To avoid processing a
node more than once, we use a boolean visited array. For simplicity, it is assumed
that all vertices are reachable from the starting vertex.For example, in the following
graph, we start traversal from vertex 2. When we come to vertex 0, we look for all
adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited
vertices, then 2 will be processed again and it will become a non-terminating
process. A Breadth First Traversal of the following graph is 2, 0, 3, 1.

Depth First Search or DFS for a Graph


Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a
tree. The only catch here is, unlike trees, graphs may contain cycles, so we may
come to the same node again. To avoid processing a node more than once, we use a
boolean visited array. For example, in the following graph, we start traversal from
vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also
an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed
again and it will become a non-terminating process. A Depth First Traversal of the
following graph is 2, 0, 1, 3.

Das könnte Ihnen auch gefallen