Академический Документы
Профессиональный Документы
Культура Документы
AFFILIATED
TO
PONDICHERRY UNIVERSITY
EC T33 - DATA STRUCTURES AND ALGORITHMS Questions and Answers II Year - III Semester
ELECTRONICS AND COMMUNICATION ENGINEERING
Page 1
UNIT I Introduction to data structures: Information and meaning Arrays in C Structures in C Stack: Definition and examples Representing stacks in C Infix, postfix and prefix UNIT II Recursion: Recursive definition and processes Recursion in C Writing recursive programs Simulating recursion Efficiency of recursion. Queues and Lists: The queue and its sequential representation Linked Lists Lists in C Simulation using linked lists Other list structures. UNIT III Trees: Binary trees Binary tree representations Huffman algorithm Representing lists as binary trees Trees and their applications Game trees. UNIT IV Sorting: General background Exchange sorts Selection and tree sorting Insertion sorts Merge and radix sorts Searching: Basic search techniques Tree searching General search trees Hashing UNIT V Graphs and their applications: Graphs A flow problem Linked representation of graphs Graph traversal and spanning forests Storage management: General lists Automatic list management Dynamic memory management.
Page 2
Page 3
7. Define Non-Linear Data Structure Non-linear data structures do not maintain any linear relationship between their elements, e.g. Tree and Graphs. 8. What is meant by an abstract data type? An ADT is a set of operation. Abstract data types are mathematical abstractions. Eg.Objects such as list, set and graph along their operations can be viewed as ADT's. 9. What are the operations of ADT? Union, Intersection, size, complement and find are the various operations of ADT. 10. Give some examples for linear data structures? 1. Stack 2. Queue 11. Define Dynamic Data structure. It becomes possible to allocate old storage when it is needed and to discard old storage when it is needed during the program of execution. 12. Define Static Data Structure. It becomes to fixed amount of storage must be pre allocated, remain through correct the execution of the program. 13. List the operation performed by the data structure. Operating to create and destroy a data structure Insert element into the data structure Delete elements from to data structure Access elements with in a data structure.
14. Define list. A list is an ordered set containing of a variable with number of elements to which insertion and deletion can be made. 15. Define an array? An array is a group of logically related data items of the same data type addressed by a common name and all items are stored in contiguous memory. Page 4
21. How do you test for an empty stack? The condition for testing an empty stack is top = 0. 22. Name two applications of stack? a) Stack is used to explain the processing of subroutine calls and their returns. b) Recursive procedures and evaluation of expressions can be implemented using stack. 23. Define a suffix expression. The notation used to write the operator at the end of the operands is called suffix notation. Suffix _ operand operand operator Page 5
28. Explain the usage of stack in recursive algorithm implementation? In recursive algorithms, stack data structures is used to store the return address when a recursive call is Encountered and also to store the values of all the parameters essential to the current state of the procedure. 29. What is space complexity? The space complexity of an algorithm is the amount of memory it needs to run to completion. 30. What is time complexity? The time complexity of an algorithm is the amount of computer time it needs to run to completion. 31. Define Algorithm? Algorithm is a solution to a problem independent of programming language. It consist of set of finite steps which, when carried out for a given set of inputs, produce the corresponding output and terminate in a finite time. 32. Define Program?
Page 6
Page 7
Primitive / Non-primitive: Primitive data structures are basic data structure and are directly operated upon machine instructions, e.g., integer, character, strings Non-primitive data structures are derived from primitive data structures, e.g., structure, union
Homogeneous/Heterogeneous In homogeneous data structures all elements are of the same type.
Page 8
Static/Dynamic In static data structures memory is allocated at the time of compilation. In dynamic data structures memory is allocated at run-time, through functions such as malloc, calloc, etc. Linear / Non-linear Linear data structures maintain a linear relationship between their elements, e.g., array, stack, Queues Non-linear data structures do not maintain any linear relationship between their elements, e.g. Tree and Graphs. 2. Explain in detail about arrays in c and its types with examples Arrays The very common linear structure is array. Since arrays are usually easy to traverse, search and sort, they are frequently used to store relatively permanent collections of data. An array is a list of a finite number n of homogeneous data elements (i.e., data elements of the same type) such that: a) The elements of the array are referenced respectively by an index consisting of n consecutive numbers. b) The elements of the array are stored respectively in successive memory locations. For example, To create a collection of five integers, one way to do it, is to declare five integers directly: int a, b, c, d, e Suppose user need to find average of 100 numbers. No need to declare 100 variables. int a, b, c, d, e, f, g, h, i, j, k, l, m, n... etc., An easier way is to declare an array of 100 integers: int a[100]; Page 9
int b;
6
You place a value into b with the statement
a[2] a[3]
b=6;
You place a value into a with the statement like: array index
a[2]=6;
datatype array_name [size]; Subscript Example: int a[5]; The five separate integers inside this array are accessed by an index. All arrays start at index zero and go to n-1 in C. Thus, int a[5]; contains five elements. For example: a[0] = 12; a[1] = 9; a[2] = 14; a[3] = 5; a[4] = 1;
Operations of Array Two basic operations in an array are storing and retrieving (extraction) Storing: A value is stored in an element of the array with the statement of the form, Page 10
1028
Page 11
for(i=0;i<5;i++) a[i]=0;
for(i=0;i<5;i++) /* Print array elements */ printf(%d\n, a[i]); Advantages: Reduces memory access time, because all the elements are stored sequentially. By incrementing the index, it is possible to access all the elements in an array. Reduces no. of variables in a program. Easy to use for the programmers. Disadvantages: Wastage of memory space is possible. For example: Storing only 10 elements in a 100 size array. Here, remaining 90 elements space is waste because these spaces cant be used by other programs till this program completes its execution. Storing heterogeneous elements are not possible. Array bound checking is not available in C. So, manually we have to do that.
Program #include <stdio.h> main() { int a[5]; /* array declaration */ for(int i = 0;i<5;i++) Page 12
The two-dimensional array will be represented in memory by a block of m*n sequential memory locations. Specifically, the programming languages will store the array either 1. Column by column, i.e. column-major order, or 2. Row by row, i.e. row-major order. 3.Write C program for sorting the given numbers using single dimension array #include<stdio.h> #include<conio.h> void main() { int a[10],t;
Page 13
A structure is a custom data type defined by the programmer. It can hold a collection of variables of different data types (unlike arrays, in which all the data elements are the same type). The data items in a structure are usually related (different kinds of information about a person, or about a part, or about an account, etc.) Each data item in a structure is called a member. Sometimes these members are also called fields. struct: Declares a structure, an object consisting of multiple data items that may be of different types. 3.2 DEFINING A STRUCTURE: Syntax: struct tag { data-type member 1; data-type member 2; data-type member m; }; Here, struct is the required keyword; tag (optional) is a name that identifies structures of this type; and member1, meber2, , member m are individual member declarations. The individual members can be ordinary variables, pointers, arrays, or other structures. A storage class cannot be assigned to an individual member, and individual members can not be initialized within a structure type declaration. ARRAYS IN THE STRUCTURE: The derived data types like array can be included in the structure as a member. Example: struct student
optional
Page 16
OR
POINTERS TO STRUCTURES: The address of a given structure variable can be obtained by using the & operator. Pointers to structures, like all other pointer variables may be assigned addresses. The following statements illustrate this concept. Example: struct student { int regno; char name[20]; char dept[10]; int year; }; 6.Define and declare a structure for student record Struct student Page 17
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
Page 18
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} . Deleting an element from a stack. (Called POP operation) 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} begin if top = 0 then stackempty; item := stack(top); Page 19
6
top
6 8 4
Stack
PEEK
operation
6 8 4
Stack
Algorithm: PEEK(STACK, TOP) BEGIN /* Check, Stack is empty? */ if (TOP == -1) then print Underflow and return 0. else item = STACK[TOP] / * stores the top element into a local variable */ return item end / * returns the top element to the user */
8.Write a C Code to implement the operations of stack using array data structure #include<stdio.h> #include<conio.h> #include<stdlib.h> #define size 5 int s[size],top,i,item,choice; //Push Operation void push(int item) { top++; s[top]=item; } //Pop Operation int pop() Page 20
Page 22
10.Discuss the algorithm in detail to convert the given infix expression to postfix expression
Algorithm:
Step 1: Initialize the stack. Step 2: While (INSTR!=NULL) Step 3: ch=get the char from INSTR Step 4: if (ch==( ) then Push ch the stack. else if (ch==)) then Pop the data from the stack and append the data into POSTSTR. Until ( is read from the stack. else while (precedence(top)>=precedence(ch)) Pop data and append to POSTSTR. Step 5: Push ch into the stack. Step 6: Pop all the elements stack and append POSTSTR until the stack is empty.Example: Consider the equation, a+b*c Its postfix expression is, abc*+ It is obtained by the following steps Symbol Stack Postfix a + A + + A b + Ab * +* Ab c +* Abc abc*+ Thus the Postfix Expression is obtained. 11.Write and explain the procedure to evaluate the postfix expression Algorithm: Opnd stack=empty stack /* scan the input stack*/
Page 23
Page 24
Page 25
Page 26
Page 27
List three examples that uses linked list? Polynomial ADT Radix sort Multi lists
Page 28
Part-B 1. Explain how recursion is implemented using stacks? Recursion is the name given to the technique of defining a set or a process in terms of itself. The factorial function is FACTORIAL(N) = 1, if N = 0 N * FACTORIAL (N-1), otherwise The facility available to implement recursion by the programmer is the procedure (function in subroutine). Procedures in programming languages are a convenience to the programmer since they enable him to express just once an algorithm, which is required in many places in a program. Recursive Procedure A Procedure that contains a procedure call to itself or a procedure call to a second procedure, which eventually causes the first procedure to be called, is known as a recursive procedure. Two types of recursion 1. Recursively defined functions. Ex. Factorial 2. Recursive use of a procedure Ex: Ackermanns function. The four parts of iterative process: Initialization parameters of fix are set to their initial values. Decision determine whether to remain in the loop Computation. Update The decision parameter is updated to transfer to the next interaction result. General algorithm for recursive procedure 1. Save the parameters, local variables and return address 2. If the base criterion has been reached, then perform the final computation and go to step 3; otherwise, perform the partial computation and go to step 1. 3. Restart the most recently saved parameters, local variables, and return address, go to this return address Algorithm FACTORIAL
Page 29
2. Write Code for Fibonacci Series Generation upto n terms using recursion #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { int n; int x=-1,y=1; void fibo(int,int,int); clrscr(); printf("\t\t\FIBONACCI SERIES USING RECURSION"); printf("\nENTER THE NUMBER:"); scanf("%d",&n); printf("\nFIBONACCI SERIES IS\n"); fibo(n,x,y); getch(); } void fibo(int n1,int a,int b) { int c; if(n1<=0) { exit(0); } else { c=a+b; printf("\n%d",c); a=b; b=c; Page 30
Page 31
Page 32
Page 33
Page 34
Page 35
Page 36
7. Explain doubly linked linear lists? Doubly Linked Linear List In certain applications the links are used to denote the predecessor and successor of a node. The link denoting the predecessor of a node is called the left link and that denoting its successor is right link. A list containing this type of node is called a doubly linked linear list or a two-way chain. Insertion General algorithm for inserting a node to the left of a given node in a doubly linked list 1. Obtain a new node and set its fields. 2. If the list is empty Then insert the node in the list Update left and right pointers to the list and return. 3. If the node is to be inserted at the front of the list then insert the node Update the left pointer to the list and return. 4. Insert the node in the middle of the list and return. Procedure DOUBINS (I,R,M,X) The insertion is to be performed to the left of a specified node with its address given by the pointer variable M. The information is in X. 1. NEW NODE 2. INFOR(NEW) X 3. If R = NULL Then LPTR(NEW) RPTR(NEW) NULL L R NEW Return 4. If M = L Then LPTR(NEW) NULL RPTR(NEW) M LPTR(M) NEW L NEW Return 5. LPTR(NEW) LPTR(M) RPTR(NEW) M LPTR(M) NEW RPTR(LPTR(NEW)) NEW Return Deletion Possibilities in deletion
Page 37
Explain the linked list implementation of stack ADT in detail? _ Definition for stack _ Stack model _ Figure _ Pointer-Top _ Operations Coding
Page 38
Page 39
represents
hierarchical
2. Define leaf? In a directed tree any node which has out degree o is called a terminal node or a leaf. 3. What is meant by directed tree? Directed tree is an acyclic diagraph which has one node called its root with indegree o whille all other nodes have indegree I. 4. What is a ordered tree? In a directed tree if the ordering of the nodes at each level is prescribed then such a tree is called ordered tree. 5. What are the applications of binary tree? Binary tree is used in data processing. a. File index schemes b. Hierarchical database management system 10. What are the two methods of binary tree implementation? Two methods to implement a binary tree are, a. Linear representation. b. Linked representation 11. What is meant by traversing? Traversing a tree means processing it in such a way, that each node is visited only once. 12. What are the different types of traversing? The different types of traversing are a. Pre-order traversal-yields prefix from of expression. b. In-order traversal-yields infix form of expression. c. Post-order traversal-yields postfix from of expression. 13. Define pre-order traversal? Pre-order traversal entails the following steps; a. Process the root node b. Process the left subtree
Page 40
Page 41
A
C
TREE TERMINOLOGY:ROOT: A unique node to which all sub trees are attached is called as root of a tree. Degree of a node: It is termed as number of subtrees of the node. Leaf or terminal nodes: The nodes which are having degree zero is called as leaf or terminal nodes. Internal nodes: The nodes other than the root and the leaves are known as internal nodes. Parent nodes: A node which is having further sub branches are called as parent node of that sub tree. From e.g.: B&C are parent nodes Predecessor: The node that occurs previous to some other nodes is called as predecessor. Successor: The node that occurs next to some other nodes is called as successor. Level of a tree: Root node will be at level 0. Its children will be at level 1. Grand children will be at level 2 and so on. Height of the tree:
Page 42
Page 43
2 4 5
3 6 7
Root-1 Degree of 1- 2. Degree of 2- 2. Degree of 3- 2. Levels are 4,5,6,7. Internal node-2,3. Parent node-2,3. Level-1-0. 2,3-1. 4, 5, 6, 7-2. Sibilings:4,5,6,7,2,3. Height:2
Page 44
In binary tree, each node has : 1) Left child, 2) Right child, 3) Data piece. - The left child is the left link which points left sub tree of a node. - the right child is the right link which points the right sub tree of a node. 1 2 5 6 7 6 7 12 1 3 5 13
Advantages: 1) No wastage of memory. 2) No depth is required 3) Insertion and deletion are easy to process. 4) No need to adjust the list. Disadvantages: 1) No direct access of nodes 2) Additional memory is required.
Page 45
0 1 2 3 4 a b c d e
A B C 0 1 2 3 4
D E 5 6
Page 46
BAC
DBEAC
421536
Page 47
ABC
ABDEC
E E
124356
6
Postorder traversal: To traverse a non empty binary tree in post order fashion, then 1) Traverse the right sub tree in post order. 2)
A Traverse the left sub tree in pre order. A 1
4 5 6
-BCA
DEBCA
425631
In order
Void ignored (node*root) (node*root) { if (root! =NULL) { In order(root->left); {
Pre order
Void pre order (node*root) if (root! =NULL) { printf(root->data);
Post order
Void post order { if (root! =NULL) { Post order(root->left);
Page 48
1 5 1 8
Procedure to construct a Binary search tree: 1. Place the first element as root. 2. When placing the element at the next level, a. Compare the value of in element in the root. b. If the value of in element is smaller place it on the left sub tree. c. Otherwise place it on the right side. Eg. 78,24,65,41,51,26,81,100,88. 7 8 7
24 65 41 51 88 8 1 10 0
26
Page 49
Operator must be the parent node and operands are child nodes. Eg: A= B*C
=
* C B
Page 50
Head
A B C E G D F
Page 51
Page 52
ALGORITHM: INPUTS; For n number of symbols in the original alphabet. Frequency[i]-it states frfequency of symbols -array of size n. -i denotes the i symbol Code[i]- denotes the code of the symbol. Position[i]-use to identify a point in the tree from which it starts its constructing code for a symbol in the alphabet Isleft-> denotes the operations determines either zero or one to be placed in front of code when climbing the tree. Info->the frequency of occurrence of the symbols. Rootnodes-> points the root of a partial binary tree. Pqinsert->it is an operation which inserts a pointer into the priority queue. Pqmindelete->an operation which removes the pointer to the node with info value from priority queue
Game Trees :
Game tree is an application of trees for tic-tac-toe game. - Game trees are used to determine the best move in tic-tac-toe game from the given board position. - By using the game trees, the best next move can be determined by considering all possible moves and resulting positions. - The move selected should be the one that results in the board position with highest value.
Evaluation Function :
The evaluation is a function that accepts a board position and indication of a player (x or o) and returns a numerical value that represents the position for the next player. - The largest value returned by the function is the better position. - The winning position yields the largest possible value and the losing position yields the smallest value. - Applying static evaluation function to a board position ,the value of the winner can be calculated.
Page 54
Evaluation Condition :
The no.of rows, columns, diagonals remaining possible to move for 1 player minus the no.of places remaining open for the opponent. - This evaluation condition is static and evaluates a static board position. - So it can only look for the current board position. - It does not look ahead for the possible conditions.
Look ahead level : Look ahead level of a game tree defines the future move of the players. - Starting at any position, it is possible to construct a tree of possible board positions that may result for next move.
Minimax Algorithm :
Minimax algorithm uses static evaluation function which gives the best move for a current board position. Minimax (Player,Board) If (game over in current board position) return winner of the game. Children = all legal moves for player from current board position. If (maxturn) return maximum score of calling minimax on all the children. Else (ministurn)
Page 55
Page 56
Unit-4 Sorting 1. What is meant by sorting? Ordering the data in an increasing or decreasing fashion according to some relationship among the data item is called sorting. 2. What are the two main classifications of sorting based on the source of data? a. Internal sorting b. External sorting 3. What is meant by external sorting? External sorting is a process of sorting in which large blocks of data stored in storage devices are moved to the main memory and then sorted. 4. What is meant by internal sorting? Internal sorting is a process of sorting the data in the main memory.
5. What are the various factors to be considered in deciding a sorting algorithm? a. Programming time
Page 57
Page 58
Page 59
Page 60
Page 61
2. Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after the pivot (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation. 3. Recursively sort the sub-list of lesser elements and the sub-list of greater elements. Given an array x of n elements Choose an element a from specific position within the array(first element is chosen a=x[0]) The elements of x are partitioned so that pivot element a is placed in its position j with condition Elements in position 0 through j-1 is less than or equal to pivot Elements in position j+1 through n-1 is greater than pivot Quicksort two sub-arrays i.e., Repeat the same process with subarrays x[0] to x[j-1] and x[j+1] to x[n-1] Final results is sorted elements.
Partitioning Array: Given a pivot, partition the elements of the array such that the resulting array consists of: Page 62
Page 63
Page 64
Page 65
Time Complexity:
Space Complexity:
Page 66
It is in-place since it uses only a small auxiliary stack. It requires only n log(n) time to sort n items. It has an extremely short inner loop This algorithm has been subjected to a thorough mathematical analysis, a very precise statement can be made about performance issues.
Disadvantages:
It is recursive. Especially if recursion is not available, the implementation is extremely complicated. It requires quadratic (i.e., n2) time in the worst-case. It is fragile i.e., a simple mistake in the implementation can go unnoticed and cause it to perform badly.
Merge Sort
*It is based on the divide and conquer method *Merging is the process of combining two or more sorted files into a third sorted file
Technique:
*Divide the file into sub-files of size 1 *Merge adjacent pairs of files of n/2 files of size n *Repeat these process until there is only one file remaining of size n
Examples:
10 10 10 10 10 10 38 38 38 38 38 12 28 28 28 28 12 28 12 12 12 12 28 38 6 6 6 6 6 6 14 14 14 14 14 14 24 24 24 24 24 24 Conquering Dividing
Sorted list:
6 10 12 14 24 28 38
Algorithm:
Void merge split(int a[],int first,int last) { if(first<last) { Mid=(first+last)/2; Merge_split(a,first,mid); Merge_split(a,mid+1,last) Page 67
BUBBLE SORT It is the simplest way of sorting method. In this type of sorting most values are used and easy to handle. Technique:To pass through the file sequentially several times. Pass:Consist of comparing each element in the file with its successor. Compare x[i] with x[i+1] and interchange the root element if they are in proper order. Let x be an array with elements 45,40,190,99,11. Pass 1:45 40 190 99 11 x[0] is compared with x[1]. 45 > 40 interchange 40 45 190 99 11 x[1] is compared with x[2]. 45 < 190 no need to interchange 40 45 190 99 11 x[2] is compared with x[3]. Page 68
Page 69
(i) SIMPLE INSERTION SORT:This technique is very efficient if elements are very less. It is similar to the way librarian keeps the books in shelf in an increasing order. Technique:Consider an array of 10 elements to sort. Steps 1:- Compare ith item with jth item. Steps 2:- Copy the item of the jth position in jth position. Insertion sort is better than bubble sort. Consider the elements 24,6,2,12,18,8 Iteration 1:Pass 1:- x[1] < x[0] 6 < 24 interchange Page 70
24
18
18 18 18
24 8 8
8 24 24 24
Pass 5:-
interchange 6 2 12 6 2 12
Iteration 2:x[1] < x[0] 2<6 interchange 2 6 12 18 8 x[2] < x[1] 12 > 6 no need to interchange x[3] < x[2] 18 > 12 no need to interchange x[4] < x[3] 8 < 18 interchange 2 6 12 8 18 Iteration 3:2 6 12 8 x[0] < x[1] Pass 1:- Compare x[1] with x[0] x[1] < x[0] 24 < 6 interchange x: 6 24 2 12 18 Pass 2:x[2] with x[1] & x[1] with x[0] x[2] < x[1] 2 < 24 interchange 6 2 24 12 x[1] < x[0] 2<6 interchange x: 2 6 24 2 Pass 3:- Compare x[3] with x[2], then x[2] with x[1], then x[1] with x[0] x[3] < x[2] 18 24
24
18 18
8 8
Page 71
18 18
8 24 8
x[3], x[2] x[2], x[1] x[1], x[0] Pass 5:x[5], x[4] x[5], x[4] x[5], x[4] x[5], x[4] x[5], x[4] 2 2 2 2 2 6 6 6 6 6
12 12 8 8 8
18 8 12 12 12
8 18 18 18 18
24 24 24 24 24
Heap Sort *Heap sort is a method in which a binary tree is used in this method heap is created using binary tree and then heap is sorted using priority queue. Technique: *Create a heap using binary tree *Sorting-sort the elements *Heap is almost a complete binary tree and it can be either ascending tree ,descending tree Descending Heap: *The content of the each node is less than or equal to the content of its father *Root node contains largest element and the path from the root to a leaf is deacending order. Ascending heap: *The content of each node is greater than or equal to the content of its father. *Root node contains smallest element and path from the to a leaf is ascending order Consider the elements 25 57 48 38 10 Step 1:Take 25 as the root node 25 Step 2:take 57, 25 57 Heap is 57 25 Step 3: take 48, 57 25 48 91 84 33
Page 72
48
48
Technique-Sorting: Sort the heap, by deleting the root node of a heap and store at the end of the array. Binary tree from should not be disturb the tree should remain a complete binary tree. Step 1: 91 38 84 33 10 48 57 25
Step 2:
Page 73
Step 3: From the next level of root the greater value 57 is considered as root and the heap is rearranged as shown, 57 38 48 33 10 25 Step 4: 48 38 33 10 25
Page 74
Algorithm: Algorithm heap (x,n) { Repeat for k=1to n-1 /*k=>child position*/ Item=x[k];//item to be insereted i=k//position I j=(i=1)/2// obtain parent position, While parent exit and item >parent move dawn to position of child Make parent node as child obtain the position of new parent End while, End for, Insert item into its child position. i->position of child j->position of parent { for while i>0&&item>a[j] a[i]=a[j]; i=j; j=(i-1)1/2 end while a[i]=item; end for } Algorithm adjust(a,n) { item=a[0] //node to be inserted to created heap i=0; //position i=2*j+1; //obtain left child While i<=n-1; //left child exist also if(a[i]<a[j]) i=i+1 // obtain position to child End if //if item less than the largest child if(item<a[i]) then a[j]=a[i] //move largest child to parent position j=i; //makes largest child as parent i=2*j+1 //obtain position of left child for new parent else break; //proper position found } //insert item into parent postion a[j]=item; }
Page 75
Examples: 1)Simple Binary Search tree for the given list is as follows:78,65,4268,80,85 7 8 6 5 4 2 6 8 8 0 8 5
Page 76
Various operations that can be performed on Binary Search tree are: 1. Insertion of a node in a BST. 2. Deletion of an element from the BST. 3. Searching of an element in the BST. Insertion:
For a standard insertion operation, we only need to search for the proper position that the element should be put in and replace NIL by the element. If there are n elements in the binary search tree, then the tree contains (n+1) NIL pointers. Therefore, for the (n+1)th element to be inserted, there are (n+1) possible places available. Example: Let us take the following tree. Now 55 has to be inserted in the following tree. 1. Compare 55 with the root node (80) 55<80 Go to the left sub tree. 2. Compare 55 with the left child. 55>50 - Go to right branch. 3.Since no element is present at that position 55 is inserted at that position . Before insertion: 8 0 5 0 4 0 4 5 8 5 9 0
Page 77
After Insertion:
5 5
Algorithm: To insert an element: 1. First look for its appropriate position in the Binary Search tree. 2. Compare it with each node of the tree. 3. If the value is greater than the current node, move to the right side of the root else move to the left of the current node. Implementation: void insert(node *root, node*new) { if(new->data<root->data) { if(root->left=NULL)
Page 78
There are several cases in a binary search tree for the deletion operation: 1. A node with no children (leaf node). 2. A node with one child. 3. A node with two children.
Deletion of a Leaf node: This is the simplest deletion ,in which we set the left or right pointer of parent node as NULL.
Example:
From the above tree ,we want to delete the node having value 6 we will set left pointer of its parent node as NULL. That is left pointer of node having value 8is set to NULL. After Deletion:
Algorithm: 1.Search the parent of the leaf and the link to the leaf node as NULL. 2.Release the memory for the deleted node. Deletion of a node with one child: Here the inorder successor is always copied at the position of a node being deleted. Example: Before Deletion:
Page 80
After Deletion:
Algorithm: 1.Search the parent node to be deleted with only one child. 2.Assign the link of the parent node to be deleted. 3.Release the memory for the deleted node. Deletion of a node with two children: Call the node to be deleted N. Do not delete N. Instead, choose either its in-order successor node or its in-order predecessor node, R. Replace the value of N with the value of R, then delete R. Example: Before Deletion: Here if 20 has to be deleted, we will have to copy the inorder successor of node 20 (i.e. 15)at its position and set the left pointer as NULL.
Page 81
After Deletion:
Algorithm: 1. Search the parent of the node to be deleted with two children. 2. Copy the content of the inorder successor to the node to be deleted. 3. Delete the inorder successor node a)if the inorder successor node has no child ,follow the steps of deleting a leaf node. b)if the inorder successor node has one child follow the steps of deleting a node with one child. 4. Release the memory for the deleted node. 5. Replace the content of the node to be deleted with the copy of the content of the inorder successor node.
Implementation: void del(node*root, int key) { node *temp,*parent,*temp_succ; temp=search(root, key,&parent); /*Deleting a node with two children*/ Page 82
Page 83
Searching: In Searching the node which we want to search is called a key node. The key node will be compared with each node starting from the root node if value of key node is greater than current node then we search for it on right sub branch otherwise on left sub branch. If we reach to leaf node and still we do not get the value of key node then we declare Node is not present in the tree.
1 0
9 Page 84
In the above tree ,if we want to search for value 9.Then we will compare9 with the root node 10.As 9 is less than10 we will search on left sub branch. Now compare 9 with 5 ,but 9 is greater hence moved to the right branch and compared it has the value 9.Thus the desired node is searched. Algorithm: 1.Check if, root node of BST is NULL, then print the tree is Empty. 2.Otherwise,compare the newnode data with the root node value for the following conditions. a)If the content of the newnode = root node data then the node is found. b)If the content is less than root node. 1. Check left sub tree is NULL. Then print Search node not found. 2.Otherwise consider the left child as root and check the above condition. c)If the content is greater than root node. 1. Check right sub tree is NULL. Then print Search node not found. 2.Otherwise consider the right child as root and check the above condition.
Page 85
Time Complexity: The average and worst case time complexity are O(log n). Efficiency: The cost of each operation is a function of the number of nodes it must access for a balanced tree, these operations are logarithmic, or O(log N) The worst case (a fully degenerate tree) is O(N). If all permutations are equally likely, the average case is O(N log N).
Advantages: .BST involves less number of comparisons when compared to other method. The usage of memory will be reduced because of using Binary tree structure. Binary search trees are good if you do all three operation (insertion, deletion, lookup) often and have enough data to justify the added burden of more complex structures and algorithms AVL: It is abbreviated as Adelsion Velski Lendis.
Page 86
Balance factor of 5 = 2-1 = 1 Balance factor of 4 = 1 Balance factor of 7 = 0 Balance factor of 3 = 0 Therefore, the tree is an AVL tree.
Balance factor of 10 = 3-1 =2 Therefore, the tree is not an AVL tree. REPERESENTATION: AVL follows properties of binary search tree. AVL is a binary search tree with balance factor either 1,0 or -1. After insertion of any node, the balance factor becomes other than 1,0 or -1 ,then the AVL property is violated. The nodes on that path has to be readjusted, the process of readjusting the tree is known as rotation. Insertion: Four different cases of rotation is required after a insertion of a newnode.
Page 87
Rotation is a process of rebalancing the AVL tree to maintain the balance factor after insertion or deletion of a node. Types: a) Single rotation 1. LL 2. RR b) Double rotation 1. LR 2. RL Different rotations: LL:
RR:
Page 88
LR:
RL:
Page 89
After the insertion 90, the AVL property is violated,because the level of sub tree are same so single rotation is applied. II. Single rotation:right
After the insertion of 20, to the AVL tree the property of AVL is violated so right rotation is applied.
III.
Double rotation: LR
Page 90
After insertion of 35,the AVL property is violated so double rotation is applied. IV. Double Rotation:(RL)
Page 91
After the insertion of 70, the AVL property is violated so double rotation is applied.
Page 92