Trees

 

A tree is a non-linear data structure, which consists of collection of nodes connected by edges. A tree consists of a distinguished node r, called the root. In the tree of Figure 4.1, the root is A. In a tree with n number of nodes, the number of edges will be n-1. Each node except the root has one parent. Node C has A as a parent and H, I, and J as children. A B C
Level 0 Level 1 Level 2

D I J K L

E M

F

G

H

N

O

P R
Figure 4.1: An example tree

Q

Level 3

Level 4

      

Each node may have an arbitrary number of children, possibly zero. Nodes with no children are known as leaves; the leaves in the tree above are F, G, H, N, R, J, K, L, P, Q, and R. Nodes with at least one child are sometimes called internal or non-terminal nodes. In the above figure, B, C, D, E, I, M, and O are internal nodes. Nodes with the same parent are siblings; thus H, I, and J are all siblings. A is grandparent of I and I is a grandchild of A. A path from node n1 to nk is defined as a sequence of nodes n1, n2, . . . , nk such that ni is the parent of ni+1 . The length of the path is the number of edges on the path. In a tree there is exactly one path from the root to each node. For any node ni, the depth of ni is the length of the unique path from the root to n i. Thus, the root is at depth 0. The height of ni is the longest path from ni to a leaf. Thus all leaves are at height 0. The height of a tree is equal to the height of the root. For the tree in Figure 4.1, E is at depth 1 and height 2; F is at depth 2 and height 0; the height of the tree is 4. The depth of a tree is equal to the depth of the deepest leaf; this is always equal to the height of the
1 Prepared exclusively for II/IV B.Tech CSE, RVRJCCE

  

tree. If there is a path from n1 to n2, then n1 is an ancestor of n2 and n2 is a descendant of n1. The level of a node is the number of nodes on the path from the node to the root node. Degree of a node is the number of its children/subtrees. Degree of node A in figure 4.1 is 4. Degree of node M is 2. The degree of a tree is the maximum degree of any of its nodes. Degree of tree shown in figure 4.1 is 4. The sum of the depths of all nodes in a tree is known as the internal path length.

Binary Trees A binary tree is a tree in which no node can have more than two children. The average depth of a binary tree is O(√n). In the worst case the depth can be as large as n-1. A

B

C E

D

F

G

H

I

J

Figure 4.2: An example Binary Tree Types of Binary trees

A full binary tree (sometimes proper binary tree or 2-tree or strictly binary tree) is a tree in which every node other than the leaves has two children. Or, perhaps more clearly, every node in a binary tree has exactly (strictly) 0 or 2 children. A

B

C

D

E

F

G

H

I

Figure 4.3: An example Full Binary Tree
2 Prepared exclusively for II/IV B.Tech CSE, RVRJCCE

A perfect binary tree is a full binary tree in which all leaves are at the same depth or same level, and in which every parent has two children. (This is ambiguously also called a complete binary tree (see next).) An example of a perfect binary tree is the ancestry chart of a person to a given depth, as each person has exactly two biological parents (one mother and one father); note that this reverses the usual parent/child tree convention, and these trees go in the opposite direction from usual (root at bottom). A

B

C

D

E

F

G

Figure 4.4: An example Perfect Binary Tree

A complete binary tree is a binary tree in which every level, except possibly the last,( the last level is not completely filled ) is completely filled, and all nodes are as far left as possible. . This type of tree is used as a specialized data structure called a heap. A

B D H I

C E

F

G

Figure 4.5: An example Complete Binary Tree

A balanced binary tree is commonly defined as a binary tree in which the depth of the left and right subtrees of every node differ by 1 or less. Binary trees shown in above figures 4.2 to 4.5 are all balanced. Binary tree shown in the following figure 4.6 is an unbalanced binary tree, since the difference between the heights of left subtree and right subtree of node B is 2 – 0 = 2, which is greater than 1.

3

Prepared exclusively for II/IV B.Tech CSE, RVRJCCE

Figure 4. RVRJCCE . The following algorithms are described for a binary tree. exactly once.7: Tree Traversal Pre-order Traversal 1.Tech CSE. Traverse the left subtree. Such traversals are classified by the order in which the nodes are visited.6: An example Binary Tree that is not balanced Tree traversal Tree traversal (also known as tree search) refers to the process of visiting each node in a tree data structure. in a systematic way. Traverse the right subtree.A B D C E H F G Figure 4. Visit the root. 2. 4 Prepared exclusively for II/IV B. 3.

7 will visit the nodes in the order A. T. We can evaluate an expression tree. 3. G. + + * a b * c * + g f d e Figure 4. I. in the form of an expression tree. D. 2. H. F. D. B. Traverse the right subtree. B. and F. E. 2. In-order Traversal 1. G. B.7 will visit the nodes in the order A.7 will visit the nodes in the order F. D. Traverse the left subtree. In our example. One of the principal uses of binary trees is in the area of compiler design. and I. E. Application of In-order steps on the binary tree of figure 4. Traverse the left subtree. This particular tree happens to be binary. by applying the operator at the root to the values obtained by recursively evaluating the left and right subtrees. Figure 4. Traverse the right subtree. C. C.Application of these steps on the binary tree of figure 4. and the other nodes contain operators. RVRJCCE . Visit the root. and H. such as constants or variable names. C. E. I. The entire tree therefore represents (a + (b*c)) + (((d * e) + f)* g). A. 3. H. Post-order Traversal 1. Application of Post-order steps on the binary tree of figure 4. the left subtree evaluates to a + (b * c) and the right subtree evaluates to ((d *e) + f)*g. G. Expression Tree Binary trees have many important uses.8: An example expression tree 5 Prepared exclusively for II/IV B. The leaves of an expression tree are operands.8 shows an example of an expression tree. Visit the root. because all of the operations are binary.Tech CSE.

+ a b Next.Application of Pre-order traversal on the expression tree would produce prefix expression. Algorithm to convert a postfix expression into an expression tree Step 1: Read a symbol from the postfix expression. b. the node onto the stack. a '+' is read. so two pointers to trees are popped. As an example. and e are read. and a pointer to it is pushed onto the stack. a b Next. 6 Prepared exclusively for II/IV B. Step 4: Repeat the steps 1 to 3 until there are symbols to be processed in the postfix expression.Tech CSE. a new tree is formed. a. RVRJCCE . suppose the input is a b + c d e + * * The first two symbols are operands. Create a tree node for the operator. d. and for each a one-node tree is created and a pointer to the corresponding tree is pushed onto the stack. Step 2: Step 3: If symbol is an operand. Inorder traversal would produce infix expression. create a tree node for the operand and push If symbol is an operator. and form a new tree by making them right and left subtrees of operator node. Pop top two elements from the stack. so create one-node trees and push pointers to them onto a stack. c. and Post-order traversal would produce postfix expression. Push this newly formed tree onto the stack.

so we pop two tree pointers and form a new tree with a '*' as root. + c + a b d e Continuing. + * b a c + d e 7 Prepared exclusively for II/IV B. so top two trees are merged. RVRJCCE . a '*' is read.+ c d e a b Now a '+' is read.Tech CSE.

Right skewed binary tree will have only right sub trees. two trees are merged. 8 Prepared exclusively for II/IV B. and the values of all the keys in the right subtree are larger than the key value in X. X. * + * b a c + d e Skewed Binary trees : A skewed binary tree means a binary tree with either only right sub trees or only left subtrees.Tech CSE. and a pointer to the final tree is left on the stack.9: Left Skewed Binary Tree 5 8 6 4 Figure 4. in the tree. 5 8 6 4 Figure 4.10 shows right skewed binary tree. the values of all the keys in the left subtree are smaller than the key value in X.10: Right Skewed Binary Tree Search Tree ADT – Binary Search Tree Binary Search Tree is a binary tree in which.9 shows left skewed binary tree and Figure 4. Figure 4. Left skewed binary tree will have only left sub trees. for every node.Finally. RVRJCCE . the last symbol is read.

4. go to the left subtree. and 7 are to be inserted into a BST. Operations on BST 1. place to insert 6 is root node.11: Binary tree 8 2 2 9 Figure 4. go to the right subtree. 4 is compared with 6. The average depth of a binary search tree is O(log n). the algorithm reaches a leaf node. Foll owing this simple rule. To search for place to insert new element. inorder to find the place for inserting 4. algorithm should follow binary search tree property.12: Binary Search Tree The tree in Figure 4.11 is not a Binary Search Tree. to which the new element is to be inserted as left child or right child depending on its value. 4 should be inserted as the left child of 6. RVRJCCE . Since 4 is less than 6 and 6 has no left child. 8. If a new value is less than the current node's value.12 is a Binary Search Tree but the one shown in Figure 4. 6 4 9 Prepared exclusively for II/IV B.Tech CSE.5 5 7 3 3 8 7 4 1 4 6 1 9 6 2 Figure 4. where n is the number of nodes in the tree. since the tree has a node with key 2 in the right subtree of a node with key 7. else if it is greater than the current node's value. Insert : Inserting a node into Binary Search Tree can be divided into two steps:   Search for a place to put a new element. While inserting 6. Insert the new element to this place. The resulting tree after insertion would be as shown below 6 While inserting 4. As an example. because the tree is not existing. assume that the elements 6.

4. inorder to find the place for inserting 8. RVRJCCE . The FindMax routine is the same. by following right subtree. following strategy should be followed a) Find the smallest element in the right subtree of node to be deleted b) Replace the value of node to be deleted with the value of smallest element found in previous step. 6 4 7 8 2. except that branching is to the right child.  If the node is a leaf. To perform a FindMin. inorder to find the place for inserting 7. the node can be deleted after its parent adjusts a pointer to bypass the node. respectively.  If the node has two children. Since 8 is greater than 6 and 6 has no right child. It returns NULL if there is no matching node. 3.While inserting 8. Since 7 is less than 8 and 8 has no left child. 7 is compared with 8. start at the root and go left as long as there is a left child. Delete: Once the node to be deleted is found. Since 7 is greater than 6. 6 4 8 While inserting 7. 8 is compared with 6. and returns a pointer to that node. 7 should be inserted as the left child of 8.  If the node has one child. 8 should be inserted as the right child of 6. FindMin and FindMax: These routines return pointer to the smallest and largest elements in the tree. 7 is compared with 6. The stopping point is the smallest element.Tech CSE. c) Delete the smallest element in the right subtree of node to be deleted 10 Prepared exclusively for II/IV B. Find : Find searches for a node whose value matches with the element searching for. it can be deleted immediately. the following possibilities should be considered for deleting the node.

the node can be deleted after node 7 adjusts a pointer to bypass the node 8. RVRJCCE . Smallest element is 6. it can be deleted immediately. 11 Prepared exclusively for II/IV B.Consider the following Binary Search Tree. then follow the strategy given above.Tech CSE. if the node to be deleted is 8. Copy 6 into node 5. Resulting tree would be as shown below: 5 3 7 1 6 8 2 2 9 Next. 5 3 7 4 1 6 8 2 2 9 Since 4 is leaf node. if the node to be deleted is 5. 5 5 3 7 3 1 6 8 2 2 7 1 9 6 9 2 2 Next. Assume the element to be deleted is 4. First find the smallest element in the right subtree of 5.

where n is number of nodes in the binary search tree. RVRJCCE .Tech CSE.2 6 1 6 3 7 1 9 2 2 The average time complexity of all the operations discussed above is O(log n). 12 Prepared exclusively for II/IV B.6 3 7 9 2 Now. delete element 6 which is in the right subtree of 5.

t->right=NULL. t->left=NULL. printf("%d\t". preorder(t->right). t->left). struct node * insert (int ele.struct node *t) { if(t==NULL) { t=(struct node *)malloc(sizeof(struct node)).t->data). printf("%d\t".C implementation of operations on a Binary Search Tree #include<stdio.t->data). } else { if(ele < t->data) t->left = insert(ele. } } void inorder (struct node *t) { if(t!=NULL) { inorder(t->left). } void preorder (struct node *t) { if(t!=NULL) { printf("%d\t".h> struct node { int data. } return t. t->data=ele. RVRJCCE . inorder(t->right). postorder(t->right). t->right). } } void postorder (struct node *t) { if(t!=NULL) { postorder(t->left).*right. else if(ele > t->data) t->right = insert(ele. struct node *left.t->data). preorder(t->left). } } 13 Prepared exclusively for II/IV B. }.Tech CSE.

} } struct node * findmin (struct node *t) { if(t == NULL) return NULL. else return find(ele. } struct node * delete(int ele. return t. 14 Prepared exclusively for II/IV B.. struct node *t) { if(t!=NULL) { if(t->data == ele) { printf("Element found\n")..Tech CSE. struct node *t) { struct node *temp.\n"). return NULL. } else if(t->data < ele) return find(ele. while(t->right != NULL) t = t->right. } if(ele < t->data) t->left = delete(ele. while(t->left != NULL) t = t->left. return t.struct node * find (int ele. t->left). return NULL. if(t == NULL) { printf("No element to delete. t->right). else { if(t->left != NULL && t->right != NULL) { temp = findmin(t->right). return t. else if(ele > t->data) t->right = delete(ele. t->left). RVRJCCE . } struct node * findmax (struct node *t) { if(t == NULL) return NULL.t->right). } else { printf("Element not found\n").

root). m=delete(n.Exit:\nEnter your choice:\n").Preorder\n3.root). } } } 15 Prepared exclusively for II/IV B. break. *root=NULL.Inorder\n4.&n). case 3: inorder(root). scanf("%d". break. if(m!=NULL) printf("Minimum element is %d\n". } main() { int ch.n. case 5: printf("Enter the number to find:\n"). while(1) { printf("\n1. break.Postorder\n5. break. case 7: m=findmin(root).Insert\n2. if(m!=NULL) printf("Maximum element is %d\n". break. break.Delete an element\n9.t->data = temp->data. break. struct node *m.m->data). case 8: printf("Enter the element to delete:\n").Find min\n8. scanf("%d". case 4: postorder(root). break. root=insert(n. scanf("%d". case 2: preorder(root).&ch).m->data). t->right). scanf("%d". default: printf("Invalid choice\n"). case 6: m=findmax(root). } return t.&n). } else if(t->left == NULL) t = t->right. m=find(n. RVRJCCE .Find element\n6.&n). else if (t->right == NULL) t = t->left. case 9: exit(0).Tech CSE.root).Find max\n7. switch(ch) { case 1: printf("Enter the element to insert:\n"). t->right = delete(t->data.

RVRJCCE . If the case is 1 or 4 violation can be fixed by single rotation else. RR Rotation can fix the violation. in an AVL tree of height h is given by N(h) = N(h .25. This modification is called rotation. LL and RR rotations are single rotations.14: A Binary Search Tree but not an AVL 9 2 2 Height of an AVL tree is log(n + 1) + 0. 6 3 6 3 7 1 7 1 6 9 2 2 Figure 4. 16 Prepared exclusively for II/IV B. N(h).2) + 1.1) + N(h . An insertion into the left subtree of the right child of t. LR Rotation can fix the violation. 3. The minimum number of nodes. if the case is 2 or 3 violation can be fixed by double rotation. All the tree operations except insert and delete can be performed in O(log n) time. N(h) = 1. with the property that for every node in the tree. the height of the left and right subtrees can differ by at most 1.Tech CSE. but the tree in figure 4. a simple modification must be made to the tree. 2. 4.AVL trees An AVL tree is a binary search tree. If the case is 2. AVL property violation might occur at a node (call t) in four cases: 1.14 is not. Height information is kept for each node in the node structure. For h = 0. An insertion into the right subtree of the right child of t. RL Rotation can fix the violation. In order to restore the AVL property. If the case is 4. The tree in Figure 4. while LR and RL rotations are double rotations. For h = 1. An insertion into the left subtree of the left child of t.13: An example AVL Tree 8 0 Figure 4. N(h) = 2. Rotations Inserting a node into the AVL tree or deleting a node from AVL tree could violate the AVL tree property. If the case is 3.13 is an AVL tree. LL Rotation can fix the violation. During insertion. An insertion into the right subtree of the left child of t. If the case is 1.

6 4 Now assume that the next node to be inserted into the tree has a value 2. Consider the following AVL tree consisting of 2 nodes as shown below. (Difference between heights of left subtree and right subtree is 2.Tech CSE. the resulting tree would be: 6 4 4 2 2 6 2 2 17 Prepared exclusively for II/IV B. 1).LL Rotation If the AVL property gets violated at a node t due to the insertion of a node in the left subtree of the left child of t. LL Rotation can fix the violation. After inserting the node. LL Rotation should be applied to fix the violation. After applying LL Rotation on node 6. which is greater than the maximum allowed height difference. RVRJCCE . tree would be as shown below 6 4 2 This insertion causes violation of AVL property at node 6. Since the insertion is in the left subtree of left child of 6.

3 5 Now assume that the next node to be inserted into the tree has a value 7. 6 4 18 Prepared exclusively for II/IV B. RVRJCCE 7 2 2 . Consider the following AVL tree consisting of 2 nodes as shown below. 3 5 5 3 7 LR Rotation If the AVL property gets violated at a node t due to the insertion of a node in the right subtree of the left child of t.Tech CSE. After inserting the node. RR Rotation should be applied to fix the violation.RR Rotation If the AVL property gets violated at a node t due to the insertion of a node in the right subtree of the right child of t. Consider the following AVL tree consisting of 2 nodes as shown below. LR Rotation should be applied to fix the violation. Since the insertion is in the right subtree of right child of 3. the resulting tree would be as shown below. tree would be as shown below 3 5 7 This insertion causes violation of AVL property at node 3. RR Rotation can fix the violation. After applying RR Rotation on node 3.

Since the insertion is in the right subtree of left child of 6. Consider the following AVL tree consisting of 2 nodes as shown below. 3 5 19 Prepared exclusively for II/IV B. RL Rotation should be applied to fix the violation.Tech CSE. tree would be as shown below 6 4 5 This insertion causes violation of AVL property at node 6. 6 4 5 4 5 6 After applying LL Rotation on node 6. 6 5 4 RL Rotation 5 4 6 2 2 If the AVL property gets violated at a node t due to the insertion of a node in the left subtree of the rightt child of t.Now assume that the next node to be inserted into the tree has a value 5. parent is node 6 and child is node 4. RVRJCCE . the resulting tree would be as shown below. LR Rotation can fix the violation. After applying RR rotation on node 4. After inserting the node. Followed by application of LL rotation on parent node. Application of RR rotation on child node 2. LR rotation is a double rotation. resulting tree would be as shown below. In this example. It involves 1.

Application of LL rotation on child node 2. It involves 1.Now assume that the next node to be inserted into the tree has a value 4.Tech CSE. Followed by application of RR rotation on parent node. RL Rotation can fix the violation. After inserting the node. 3 5 3 4 5 4 After applying RR Rotation on node 3. the resulting tree would be as shown below. Since the insertion is in the left subtree of right child of 3. 3 4 3 5 4 5 2 2 20 Prepared exclusively for II/IV B. resulting tree would be as shown below. In this example. tree would be as shown below: 3 5 4 This insertion causes violation of AVL property at node 3. RL rotation is a double rotation. After applying LL rotation on node 5. parent is node 3 and child is node 5. RVRJCCE .

int Height(struct Avlnode *t) { if (t == NULL) return -1. t->height = Max(Height(t->left). t = LLRotate(t). t1 = t->right. return t. t1 = t->left. *right. return t. t->right = t1->left. } struct Avlnode * RLRotate(struct Avlnode *t) { t->right = LLRotate(t->right). } int Max(int a. }. } struct Avlnode * LLRotate(struct Avlnode *t) { struct Avlnode *t1. else return t->height. t1->right = t.Tech CSE. } struct Avlnode * RRRotate(struct Avlnode *t) { struct Avlnode *t1. else return b. RVRJCCE . t->height = Max(Height(t->left).#include<stdio. return t1. 21 Prepared exclusively for II/IV B. } struct Avlnode * LRRotate(struct Avlnode *t) { t->left = RRRotate(t->left).h> struct Avlnode { int value. t->left = t1->right. int b) { if (a>b) return a. t1->height = Max(t->height. Height(t->right)) + 1. t1->height = Max(Height(t1->left). Height(t1->right)) + 1. struct Avlnode *left. t->height) + 1. height. return t1. Height(t->right)) + 1. t = RRRotate(t). t1->left = t.

t->left). } Priority Queue (Heaps) A priority queue is a data structure that allows at least the following two operations: insert. return t. if ( Height(t->right) . 22 Prepared exclusively for II/IV B. A heap can be max heap or min heap. else t = LRRotate(t). In max heap. and delete_min.Height(t->right) == 2) if(elt < t->left->value) t = LLRotate(t). else t = RLRotate(t). } else if(elt > t->value) { t->right = insert(elt. } else if(elt < t->value) { t->left = insert(elt. which does the obvious thing. returns and removes the minimum element in the heap.Height(t->left) == 2) if(elt > t->right->value) t = RRRotate(t).} struct Avlnode * insert(int elt. t->left = t->right = NULL. t->right). Heap is a complete binary tree with heap property. the value at each node is smaller than the values at its children. which finds. struct Avlnode *t) { if(t == NULL) { t = (struct Avlnode *) malloc(sizeof(struct Avlnode)). RVRJCCE . if ( Height(t->left) . Height(t->right)) + 1.Tech CSE. In min heap. t->height = 0. the value at each node is bigger than the values at its children. t->value = elt. } t->height = Max(Height(t->left).

move 6 down to one level.9 1 8 5 4 D 1 3 Figure 4. Since 6 < 7. Since 3 < 7. 1. Insert: Insert operation inserts a[n] into the heap which is stored in an array whose size is n1. RVRJCCE .Tech CSE. move 3 down to one level. 7 is compared with 6.16: A Min Heap Following operations can be performed on a heap. 23 Prepared exclusively for II/IV B. in this example. Assume that the node to be inserted is 7. 8 6 3 D 3 4 5 1 2 Now. 8 6 4 3 D 7 5 1 2 Compare 7 with its parent 3.15: A Max Heap 6 6 8 D 9 2 7 2 7 5 4 Figure 4.

} 24 Prepared exclusively for II/IV B. } a[i] = item. i = i/2. RVRJCCE . item = a[n].Tech CSE. 7 is placed below 8. int n) { i = n.8 6 6 D 3 4 5 1 2 Next 7 is compared with 8. 8 7 6 D 4 5 1 2 3 Following is the C code for insert function void insert(int a[]. This time 8 > 7. while ( (i>1) && (a[ i/2 ] < item ) { a[i] = a[ i/2 ].

6 is copied into its parent’s position.e. 4 is copied into position of node 6. RVRJCCE . 8.. 3. Adjust: Rearranges the elements of heap such that the tree rooted at index i is also a max heap. 6. since 6 > 4.e.e. 4 8 6 D 7 5 1 2 3 Adjust compares 4 with the biggest of its children (8 and 7) i. Consider the following complete binary tree which is not a heap because the element at root is violating heap property. 8 is copied into its parent’s position 8 8 7 6 D 3 5 1 2 Next.. since 8 > 4. Since 3 < 4. 4 is compared with the biggest child of 6 i. 8 6 6 D 3 7 5 1 2 Next. 4 is compared with the biggest child of 8 i. 25 Prepared exclusively for II/IV B.Tech CSE..2.

RVRJCCE .int i. Delete Max: Delete Max deletes the biggest element of heap. item = a[i]. 8 6 4 D 3 26 7 5 1 2 Prepared exclusively for II/IV B. Adjust is invoked on root.Tech CSE. while (j <= n) do { if ((j < n) && (a[j] < a[j+1])) then j = j + 1. } a[ j/2 ] = item. 7 5 1 2 void Adjust(int a[]. if (item >= a[j]) then break. } 3. It operates by the following steps: 1.int n) { j = 2*i.8 6 4 D 3 The resulting tree is a heap. j = 2j. Consider the following heap. which is at root node. to rearrange the elements of tree such that the resulting tree is a heap. a[ j/2 ] = a[j]. The value of last node is copied into the root node 2.

Delete Max will first copy the value of last node into root node of tree. Adjust(a. level by level. int n) { if (n ==0) then { printf(“Heap is empty”). } a[1] = a[n]. } 4. 1 4 1 4 3 7 6 7 27 2 6 5 2 3 5 Prepared exclusively for II/IV B. Green coloured node denotes the node on which adjust is called. Delete Max invokes adjust on root by excluding last node. Heapify: Heapify creates a heap out of the given array/binary tree. 1.Tech CSE. RVRJCCE . return. until the root is reached. Resulting tree is: 3 6 4 D 3 7 5 1 2 The above tree is not a heap because heap property is violated at root. 7 6 3 5 4 1 2 void DelMax(int a[]. Next. Heapify begin by calling adjust for the parents of leaf nodes and then work its way up. Following figures shows the sequence of changes made to the initial tree as a result of applying heapify. yielding a tree which is a heap. n-1).

The algorithm swaps the first element (element at root )with the last element in the array. 7 5 6 4 4 5 6 1 2 6 3 1 2 3 7 3 5 4 4 7 5 1 2 3 1 2 6 7 28 Prepared exclusively for II/IV B.Tech CSE. This process is repeated till the second element of the array. green colored nodes represent nodes that are to be swapped.1 1 6 4 7 5 6 7 2 3 4 2 3 5 1 7 7 6 1 4 6 4 Heap Sort 2 3 5 2 3 5 This algorithm requires the input array to be a heap. Heap sort strategy is shown in following figures. then invokes adjust on the first element by excluding last element. RVRJCCE .

5 4 2 4 3 2 1 3 1 6 7 5 6 7 4 1 3 2 2 7 3 1 5 6 4 5 6 7 3 1 1 2 2 7 3 4 5 6 4 5 1 6 7 2 1 3 2 3 4 5 6 7 4 5 6 7 C program for Heap Sort is given below.Tech CSE. RVRJCCE . 29 Prepared exclusively for II/IV B.

printf(“\nEnter size of Heap:”). RVRJCCE . for(i = n/2. t. i<= n. a[25]. while (j <= n) do { if ((j < n) && (a[j] < a[j+1])) then j = j + 1. } Time complexity of Heap Sort is O(n log n). } a[ j/2 ] = item. n. Heapsort(a. for(i = 1. item = a[i]. item. for( i = n. int n) { int i.i.Tech CSE. } void Heapsort(int a[]. a[ j/2 ] = a[j]. i++) printf(“%d ”. for(i = 1.n).n). i-1). Adjust(a. i >= 1.int n) { int j.n). 1. Heapify(a. i--) Adjust(a.h> void Adjust(int a[].&a[i]). i++) scanf(“%d”.#include<stdio. a[i] = a[1]. a[1] = t. printf(“\nEnter elements of heap:”). i<= n. if (item >= a[j]) then break. } } void main() { int i. } void Heapify(int a[].int i. printf(“\n Sorted Array: \n”). int n) { int i. i--) { t = a[i]. j = 2*i. i > 1. scanf(“%d”.&n). 30 Prepared exclusively for II/IV B. j = 2j.a[i]).